Traversing a list until certain criterion is metBigInt for Standard ML/NJHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How do you split a list into evenly sized chunks?Does functional programming replace GoF design patterns?Getting the last element of a listHow to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?
Windows 10 deletes lots of tiny files super slowly. Anything that can be done to speed it up?
Garage door sticks on a bolt
Why most footers have a background color has a divider of section?
Is it possible to take a database offline when doing a backup using an SQL job?
How to compare integers in Tex?
How do I introduce dark themes?
Which Catholic priests were given diplomatic missions?
Is it mandatory to use contractions in tag questions and the like?
How many space launch vehicles are under development worldwide?
How deep is the liquid in a half-full hemisphere?
Why would an airline put 15 passengers at once on standby?
Should I be on the paper from another PhD student that I constantly went on his meetings?
How many stack cables would be needed if we want to stack two 3850 switches
Why do Russians sometimes spell "жирный" (fatty) as "жырный"?
How to say "respectively" in German when listing (enumerating) things
Difference between two vector layer
If someone asks a question using “quién”, how can one shortly respond?
Why, even after his imprisonment, do people keep calling Hannibal Lecter "Doctor"?
Can an energy drink or chocolate before an exam be useful ? What sort of other edible goods be helpful?
Speed and Velocity in Russian
Is determiner 'a' needed in "one would call such a value a constant"?
What is the meaning of colored vials next to some passive skills
How to study endgames?
Why isn't there armor to protect from spells in the Potterverse?
Traversing a list until certain criterion is met
BigInt for Standard ML/NJHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How do you split a list into evenly sized chunks?Does functional programming replace GoF design patterns?Getting the last element of a listHow to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I would like to create a simple SML program that traverses a list from left to right.Let's say I have a list of N items of K different types.For example the list 1 3 1 3 1 3 3 2 2 1
has 10 numbers of 3(1,2,3)
types.
What I would like to to is go through this list from left to right and stop when i have found all K different numbers.In this case I would stop right after stumbling upon the first 2.
This could be done by spliting the list in head and tail in each step and processing the head element.However how could I keep track of the different numbers I have found?
This could be done in C/C++ by simply holding a counter and a boolean array with K elements. If i stumble upon an element i with bool[i]=false
i make it true and counter=counter+1
.
It is stated though that arrays are not the best option for SML so i was wondering if i have to use another data structure or if i have to create a new function to check each time if i have seen this element before(this would cost in time complexity).
list functional-programming sml smlnj
add a comment
|
I would like to create a simple SML program that traverses a list from left to right.Let's say I have a list of N items of K different types.For example the list 1 3 1 3 1 3 3 2 2 1
has 10 numbers of 3(1,2,3)
types.
What I would like to to is go through this list from left to right and stop when i have found all K different numbers.In this case I would stop right after stumbling upon the first 2.
This could be done by spliting the list in head and tail in each step and processing the head element.However how could I keep track of the different numbers I have found?
This could be done in C/C++ by simply holding a counter and a boolean array with K elements. If i stumble upon an element i with bool[i]=false
i make it true and counter=counter+1
.
It is stated though that arrays are not the best option for SML so i was wondering if i have to use another data structure or if i have to create a new function to check each time if i have seen this element before(this would cost in time complexity).
list functional-programming sml smlnj
add a comment
|
I would like to create a simple SML program that traverses a list from left to right.Let's say I have a list of N items of K different types.For example the list 1 3 1 3 1 3 3 2 2 1
has 10 numbers of 3(1,2,3)
types.
What I would like to to is go through this list from left to right and stop when i have found all K different numbers.In this case I would stop right after stumbling upon the first 2.
This could be done by spliting the list in head and tail in each step and processing the head element.However how could I keep track of the different numbers I have found?
This could be done in C/C++ by simply holding a counter and a boolean array with K elements. If i stumble upon an element i with bool[i]=false
i make it true and counter=counter+1
.
It is stated though that arrays are not the best option for SML so i was wondering if i have to use another data structure or if i have to create a new function to check each time if i have seen this element before(this would cost in time complexity).
list functional-programming sml smlnj
I would like to create a simple SML program that traverses a list from left to right.Let's say I have a list of N items of K different types.For example the list 1 3 1 3 1 3 3 2 2 1
has 10 numbers of 3(1,2,3)
types.
What I would like to to is go through this list from left to right and stop when i have found all K different numbers.In this case I would stop right after stumbling upon the first 2.
This could be done by spliting the list in head and tail in each step and processing the head element.However how could I keep track of the different numbers I have found?
This could be done in C/C++ by simply holding a counter and a boolean array with K elements. If i stumble upon an element i with bool[i]=false
i make it true and counter=counter+1
.
It is stated though that arrays are not the best option for SML so i was wondering if i have to use another data structure or if i have to create a new function to check each time if i have seen this element before(this would cost in time complexity).
list functional-programming sml smlnj
list functional-programming sml smlnj
edited Mar 28 at 21:15
Labyrinthian
asked Mar 28 at 19:44
LabyrinthianLabyrinthian
291 silver badge6 bronze badges
291 silver badge6 bronze badges
add a comment
|
add a comment
|
1 Answer
1
active
oldest
votes
how could I keep track of the different numbers I have found?
[...] in C/C++ by [...] a boolean array with K elements
Abstractly I would call the data structure you want a bit set.
I'll give you two answers, one using a sparse container and one using a bit set.
Sparse
I'd use a list to keep track of the elements you've already seen:
fun curry f x y = f (x, y)
val empty = []
fun add x set = curry op:: x set
fun elem x set = List.exists (curry op= x) set
fun seen k xs =
let fun seen_ 0 _ _ = true
| seen_ _ [] _ = false
| seen_ k (x::xs) set =
if elem x set
then seen_ k xs set
else seen_ (k-1) xs (add x set)
in seen_ k xs empty end
You could also use a balanced binary tree as set type; this would reduce lookup to O(lg n). The advantage of using an actual container (list or tree) rather than a bit array is that of sparse arrays/matrices. This works for ''a list
s.
Bit set
[...] boolean array with K elements [...]
If i stumble upon an element i [...]
Until this point, you haven't said that elements are always unsigned integers from 0 to K-1, which would be a requirement if they should be representable by a unique index in an array of length K.
SML has a module/type called Word
/ word
for unsigned integers (words). Adding this constraint, the input list should have type word list
rather than ''a list
.
When you make an array of primitive types in many imperative, compiled languages, you get mutable, unboxed arrays. SML's Array type is also mutable, but each bool
in such an array would be boxed.
An easy way to get an immutable, unboxed array of bits would be to use bitwise operations on an IntInf
(SML/NJ; implementations vary); it would automatically grow as a bit is flipped. This could look like:
fun bit x = IntInf.<< (1, x)
val empty = IntInf.fromInt 0
fun add x set = IntInf.orb (set, bit x)
fun elem x set = IntInf.> (IntInf.andb (set, bit x), 0)
The function seen
would be the same.
The fact that k
is decreased recursively and that set
grows dynamically means that you're not restricted to elements in the range [0,K-1], which would have been the case with an array of size K.
Example use:
- seen 5 [0w4, 0w2, 0w1, 0w9];
val it = false : bool
- seen 5 [0w1, 0w2, 0w3, 0w4, 0w8];
val it = true : bool
This solution uses a lot of memory if the elements are large:
- seen 1 [0w100000000];
*eats my memory slowly*
val it = true : bool
Additional things you could do:
- Create a module,
structure BitSet = struct ... end
that encapsulates an abstract type with the operationsempty
,add
andelem
, hiding the particular implementation (whether it's anIntInf.int
, or abool Array.array
or an''a list
). - Create a function,
fun fold_until f e xs = ...
that extracts the recursion scheme ofseen_
so that you avoid manual recursion; a regularfoldl
is not enough since it continues until the list is empty. You could build this using error-aware return type or using exceptions. - Consider Bloom filters.
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405721%2ftraversing-a-list-until-certain-criterion-is-met%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
how could I keep track of the different numbers I have found?
[...] in C/C++ by [...] a boolean array with K elements
Abstractly I would call the data structure you want a bit set.
I'll give you two answers, one using a sparse container and one using a bit set.
Sparse
I'd use a list to keep track of the elements you've already seen:
fun curry f x y = f (x, y)
val empty = []
fun add x set = curry op:: x set
fun elem x set = List.exists (curry op= x) set
fun seen k xs =
let fun seen_ 0 _ _ = true
| seen_ _ [] _ = false
| seen_ k (x::xs) set =
if elem x set
then seen_ k xs set
else seen_ (k-1) xs (add x set)
in seen_ k xs empty end
You could also use a balanced binary tree as set type; this would reduce lookup to O(lg n). The advantage of using an actual container (list or tree) rather than a bit array is that of sparse arrays/matrices. This works for ''a list
s.
Bit set
[...] boolean array with K elements [...]
If i stumble upon an element i [...]
Until this point, you haven't said that elements are always unsigned integers from 0 to K-1, which would be a requirement if they should be representable by a unique index in an array of length K.
SML has a module/type called Word
/ word
for unsigned integers (words). Adding this constraint, the input list should have type word list
rather than ''a list
.
When you make an array of primitive types in many imperative, compiled languages, you get mutable, unboxed arrays. SML's Array type is also mutable, but each bool
in such an array would be boxed.
An easy way to get an immutable, unboxed array of bits would be to use bitwise operations on an IntInf
(SML/NJ; implementations vary); it would automatically grow as a bit is flipped. This could look like:
fun bit x = IntInf.<< (1, x)
val empty = IntInf.fromInt 0
fun add x set = IntInf.orb (set, bit x)
fun elem x set = IntInf.> (IntInf.andb (set, bit x), 0)
The function seen
would be the same.
The fact that k
is decreased recursively and that set
grows dynamically means that you're not restricted to elements in the range [0,K-1], which would have been the case with an array of size K.
Example use:
- seen 5 [0w4, 0w2, 0w1, 0w9];
val it = false : bool
- seen 5 [0w1, 0w2, 0w3, 0w4, 0w8];
val it = true : bool
This solution uses a lot of memory if the elements are large:
- seen 1 [0w100000000];
*eats my memory slowly*
val it = true : bool
Additional things you could do:
- Create a module,
structure BitSet = struct ... end
that encapsulates an abstract type with the operationsempty
,add
andelem
, hiding the particular implementation (whether it's anIntInf.int
, or abool Array.array
or an''a list
). - Create a function,
fun fold_until f e xs = ...
that extracts the recursion scheme ofseen_
so that you avoid manual recursion; a regularfoldl
is not enough since it continues until the list is empty. You could build this using error-aware return type or using exceptions. - Consider Bloom filters.
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
add a comment
|
how could I keep track of the different numbers I have found?
[...] in C/C++ by [...] a boolean array with K elements
Abstractly I would call the data structure you want a bit set.
I'll give you two answers, one using a sparse container and one using a bit set.
Sparse
I'd use a list to keep track of the elements you've already seen:
fun curry f x y = f (x, y)
val empty = []
fun add x set = curry op:: x set
fun elem x set = List.exists (curry op= x) set
fun seen k xs =
let fun seen_ 0 _ _ = true
| seen_ _ [] _ = false
| seen_ k (x::xs) set =
if elem x set
then seen_ k xs set
else seen_ (k-1) xs (add x set)
in seen_ k xs empty end
You could also use a balanced binary tree as set type; this would reduce lookup to O(lg n). The advantage of using an actual container (list or tree) rather than a bit array is that of sparse arrays/matrices. This works for ''a list
s.
Bit set
[...] boolean array with K elements [...]
If i stumble upon an element i [...]
Until this point, you haven't said that elements are always unsigned integers from 0 to K-1, which would be a requirement if they should be representable by a unique index in an array of length K.
SML has a module/type called Word
/ word
for unsigned integers (words). Adding this constraint, the input list should have type word list
rather than ''a list
.
When you make an array of primitive types in many imperative, compiled languages, you get mutable, unboxed arrays. SML's Array type is also mutable, but each bool
in such an array would be boxed.
An easy way to get an immutable, unboxed array of bits would be to use bitwise operations on an IntInf
(SML/NJ; implementations vary); it would automatically grow as a bit is flipped. This could look like:
fun bit x = IntInf.<< (1, x)
val empty = IntInf.fromInt 0
fun add x set = IntInf.orb (set, bit x)
fun elem x set = IntInf.> (IntInf.andb (set, bit x), 0)
The function seen
would be the same.
The fact that k
is decreased recursively and that set
grows dynamically means that you're not restricted to elements in the range [0,K-1], which would have been the case with an array of size K.
Example use:
- seen 5 [0w4, 0w2, 0w1, 0w9];
val it = false : bool
- seen 5 [0w1, 0w2, 0w3, 0w4, 0w8];
val it = true : bool
This solution uses a lot of memory if the elements are large:
- seen 1 [0w100000000];
*eats my memory slowly*
val it = true : bool
Additional things you could do:
- Create a module,
structure BitSet = struct ... end
that encapsulates an abstract type with the operationsempty
,add
andelem
, hiding the particular implementation (whether it's anIntInf.int
, or abool Array.array
or an''a list
). - Create a function,
fun fold_until f e xs = ...
that extracts the recursion scheme ofseen_
so that you avoid manual recursion; a regularfoldl
is not enough since it continues until the list is empty. You could build this using error-aware return type or using exceptions. - Consider Bloom filters.
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
add a comment
|
how could I keep track of the different numbers I have found?
[...] in C/C++ by [...] a boolean array with K elements
Abstractly I would call the data structure you want a bit set.
I'll give you two answers, one using a sparse container and one using a bit set.
Sparse
I'd use a list to keep track of the elements you've already seen:
fun curry f x y = f (x, y)
val empty = []
fun add x set = curry op:: x set
fun elem x set = List.exists (curry op= x) set
fun seen k xs =
let fun seen_ 0 _ _ = true
| seen_ _ [] _ = false
| seen_ k (x::xs) set =
if elem x set
then seen_ k xs set
else seen_ (k-1) xs (add x set)
in seen_ k xs empty end
You could also use a balanced binary tree as set type; this would reduce lookup to O(lg n). The advantage of using an actual container (list or tree) rather than a bit array is that of sparse arrays/matrices. This works for ''a list
s.
Bit set
[...] boolean array with K elements [...]
If i stumble upon an element i [...]
Until this point, you haven't said that elements are always unsigned integers from 0 to K-1, which would be a requirement if they should be representable by a unique index in an array of length K.
SML has a module/type called Word
/ word
for unsigned integers (words). Adding this constraint, the input list should have type word list
rather than ''a list
.
When you make an array of primitive types in many imperative, compiled languages, you get mutable, unboxed arrays. SML's Array type is also mutable, but each bool
in such an array would be boxed.
An easy way to get an immutable, unboxed array of bits would be to use bitwise operations on an IntInf
(SML/NJ; implementations vary); it would automatically grow as a bit is flipped. This could look like:
fun bit x = IntInf.<< (1, x)
val empty = IntInf.fromInt 0
fun add x set = IntInf.orb (set, bit x)
fun elem x set = IntInf.> (IntInf.andb (set, bit x), 0)
The function seen
would be the same.
The fact that k
is decreased recursively and that set
grows dynamically means that you're not restricted to elements in the range [0,K-1], which would have been the case with an array of size K.
Example use:
- seen 5 [0w4, 0w2, 0w1, 0w9];
val it = false : bool
- seen 5 [0w1, 0w2, 0w3, 0w4, 0w8];
val it = true : bool
This solution uses a lot of memory if the elements are large:
- seen 1 [0w100000000];
*eats my memory slowly*
val it = true : bool
Additional things you could do:
- Create a module,
structure BitSet = struct ... end
that encapsulates an abstract type with the operationsempty
,add
andelem
, hiding the particular implementation (whether it's anIntInf.int
, or abool Array.array
or an''a list
). - Create a function,
fun fold_until f e xs = ...
that extracts the recursion scheme ofseen_
so that you avoid manual recursion; a regularfoldl
is not enough since it continues until the list is empty. You could build this using error-aware return type or using exceptions. - Consider Bloom filters.
how could I keep track of the different numbers I have found?
[...] in C/C++ by [...] a boolean array with K elements
Abstractly I would call the data structure you want a bit set.
I'll give you two answers, one using a sparse container and one using a bit set.
Sparse
I'd use a list to keep track of the elements you've already seen:
fun curry f x y = f (x, y)
val empty = []
fun add x set = curry op:: x set
fun elem x set = List.exists (curry op= x) set
fun seen k xs =
let fun seen_ 0 _ _ = true
| seen_ _ [] _ = false
| seen_ k (x::xs) set =
if elem x set
then seen_ k xs set
else seen_ (k-1) xs (add x set)
in seen_ k xs empty end
You could also use a balanced binary tree as set type; this would reduce lookup to O(lg n). The advantage of using an actual container (list or tree) rather than a bit array is that of sparse arrays/matrices. This works for ''a list
s.
Bit set
[...] boolean array with K elements [...]
If i stumble upon an element i [...]
Until this point, you haven't said that elements are always unsigned integers from 0 to K-1, which would be a requirement if they should be representable by a unique index in an array of length K.
SML has a module/type called Word
/ word
for unsigned integers (words). Adding this constraint, the input list should have type word list
rather than ''a list
.
When you make an array of primitive types in many imperative, compiled languages, you get mutable, unboxed arrays. SML's Array type is also mutable, but each bool
in such an array would be boxed.
An easy way to get an immutable, unboxed array of bits would be to use bitwise operations on an IntInf
(SML/NJ; implementations vary); it would automatically grow as a bit is flipped. This could look like:
fun bit x = IntInf.<< (1, x)
val empty = IntInf.fromInt 0
fun add x set = IntInf.orb (set, bit x)
fun elem x set = IntInf.> (IntInf.andb (set, bit x), 0)
The function seen
would be the same.
The fact that k
is decreased recursively and that set
grows dynamically means that you're not restricted to elements in the range [0,K-1], which would have been the case with an array of size K.
Example use:
- seen 5 [0w4, 0w2, 0w1, 0w9];
val it = false : bool
- seen 5 [0w1, 0w2, 0w3, 0w4, 0w8];
val it = true : bool
This solution uses a lot of memory if the elements are large:
- seen 1 [0w100000000];
*eats my memory slowly*
val it = true : bool
Additional things you could do:
- Create a module,
structure BitSet = struct ... end
that encapsulates an abstract type with the operationsempty
,add
andelem
, hiding the particular implementation (whether it's anIntInf.int
, or abool Array.array
or an''a list
). - Create a function,
fun fold_until f e xs = ...
that extracts the recursion scheme ofseen_
so that you avoid manual recursion; a regularfoldl
is not enough since it continues until the list is empty. You could build this using error-aware return type or using exceptions. - Consider Bloom filters.
edited Mar 29 at 13:39
answered Mar 29 at 12:28
Simon ShineSimon Shine
11k1 gold badge31 silver badges53 bronze badges
11k1 gold badge31 silver badges53 bronze badges
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
add a comment
|
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
Thank you for your answer it cleared a lot of things!What is the time complexiry of the second solution?
– Labyrinthian
Mar 29 at 19:24
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
@Labyrinthian: I don't know, what is it? :)
– Simon Shine
Apr 1 at 6:18
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405721%2ftraversing-a-list-until-certain-criterion-is-met%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown