I'm trying to figure out how to run the code Standard Meta Language:
smallest [5, ~4, 3]; returns ~4
fun smallest L =
if null (tl L)
then hd L
else if hd L < smallest (tl L)
then hd L
else smallest (tl L);
You need an SML interpretor, or compilor. There is multiple to choose from, but SML/NJ is most likely the most known/used.
Others include (but are not limited to) Moscow ML (MosML), MLKit and MLton. Where MLKit and MLton are compilers and SML/NJ and MosML are interpreters.
The wikipedia article on SML is properly a good starting point for you to learn some more about SML.
I recommend PolyML. It's got some of the better documentation for ML out there.
Related
I need a recursive function in F# that gives me the biggest value of a non empty list.
example:
biggest [2;4;5;3;9;3]
should return 9
Update 1
I'm learning recursive functions and this is an exercise from the book with no answer on it. I thought it was ok to ask here but it seems it was not a good idea. Ok, I didn't write any code example so that it seemed to be a homework exercise of a lazy guy. Anyway this is my best try:
let rec highest l =
match l with
|[] -> 0
|x::y::xs -> if x > y then highest x::xs
else highest y::xs
But this doesn't work. I cannot use F# functions, this is for learning purpose of course. So sorry if made you loose some time and thanks for your help.
Before the answer: this question is weird and Stackoverflow is probably not the best place for it.
If it's for production code, use List.max. (Puns aside, recursion isn't its own reward...)
If it's for homework, try to understand recursion instead of delegating your exercises to random people on the internet.
If it's a puzzle/code golf, this is the wrong site and it could be clearer what the requirements are.
Anyway, this can be answered as posted, with the following requirements:
The solution is tail-recursive, not just recursive. Obviously I don't want to write a function to replace List.max just to needlessly grow the stack.
The function biggest that is called in the question's code is directly the recursive one and gets no additional arguments. If I take the question literally, this seems to be a requirement, so I'm not allowed to use an accumulator.
List.max is implemented with a mutating loop and therefore doesn't qualify (link goes to F# source code). So this needs a custom implementation:
let rec biggest = function
| h1 :: h2 :: t -> biggest ((max h1 h2) :: t)
| [result] -> result
| [] -> failwith "list empty"
It's a pretty weird solution, but it does what's asked for and works for long lists.
After some days thinking on it and with some help at school I came up with this, it's an alternative solution to Vandroiy's one:
let rec max_value l =
match l with
|[] -> []
|[x] -> [x]
|(x::y::xs) -> if x<y then max_value (y::xs)
else max_value (x::xs)
thanks a lot
It seems that Ocaml batteries have comprehension syntax:
http://en.wikipedia.org/wiki/List_comprehension#OCaml
However, what module should I include to use this syntax? I already open Batteries, but it doesn't work. Or is there a more idiomatic way to do list comprehension? I can use List.map and BatList.remove_if to achieve similar results, but that is much less elegant.
Currently there're two libraries in OCaml that provide list comprehension, one was formerly a part of OCaml Batteries, another is shipped with camlp4. Neither is widely used and I, personally, do no recommend you to use any.
For list comprehension to work, you need to change the syntax of the language. This can be done with preprocessing your program, written in an extended syntax, with a camlp4 preprocessor. Also, list comprehension is not a first class citizen in OCaml community, and it is not well supported by the modern toolkits. Although, you can still easily play with it in a toplevel, for that you need, to install the list comprehension package:
opam install pa_comprehension
and load it into a toplevel, using the following directives:
# #use "topfind";;
# #camlp4o;;
# #require "pa_comprehension";;
# open Batteries;;
# [? 2 * x | x <- 0 -- max_int ; x * x > 3 ?];;
But again, my personal opinion that list comprehension is not the best way to structure your code.
Life without comprehension
The example, you provided, can be expressed using core_kernel Sequence module (an analog of the Batteries Enum)
let f n =
Sequence.(range 0 n |>
filter ~f:(fun x -> x * x > 3) |>
map ~f:(fun x -> x * 2))
Hence a filter |> map is such a common idiom there exists a filter_map function:
let f n =
Sequence.(range 0 n |>
filter_map ~f:(fun x ->
if x * x > 3 then Some (x * 2) else None))
You may notice, that this examples takes more code, than list comprehension. But as soon as your programs will start to mature from simple hello world applications with integers to something more sophisticated, you will agree that using explicit iterators is more readable and comprehensible.
Also, since libraries in Core are so consistent, you can use a simple List instead of Sequence just by substituting the latter by the former. But of course, List is eager, unlike the Sequence, so playing with max_int using lists is not a good idea.
Moreover, since all containers are monads, you can use monadic operators for mapping, like:
let odds n = List.(range 0 n >>| fun x -> x * 2 + 1)
list comprehension is already included in standard ocaml
#require "camlp4.listcomprehension";;
[ x * x | x <- [ 1;2;3;4;5] ];;
- : int list = [1; 4; 9; 16; 25]
I remember that when I showed some code that I wrote to my professor he remarked, offhand, that
It rarely matters, but it's worth noting that fold* is a little bit more efficient than fold*' in SML/NJ, so you should prefer it over fold* when possible.
I forget whether fold* was foldr or foldl. I know that this is one of those micro-optimization things that probably doesn't make a big difference in practice, but I'd like to be in the habit of using the more efficient one when I have the choice.
Which is which? My guess is that this is SML/NJ specific and that MLton will be smart enough to optimize both down to the same machine code, but answers for other compilers are good to know.
foldl is tail-recursive, while foldr is not. Although you can do foldr in a tail-recursive way by reversing the list (which is tail recursive), and then doing foldl.
This is only going to matter if you are folding over huge lists.
Prefer the one that converts the given input into the intended output.
If both produce the same output such as with a sum, and if dealing with a list, folding from the left will be more efficient because the fold can begin with head element, while folding from the right will first require walking the list to find the last element before calculating the first intermediate result.
With arrays and similar random access data structures, there's probably not going to be much difference.
A compiler optimization that always chose the better of left and right would require the compiler to determine that left and right were equivalent over all possible inputs. Since foldl and foldr take a functions as arguments, this is a bit of a tall order.
I'm going to keep the accepted answer here, but I had the chance to speak to my professor, and his reply was actually the opposite, because I forgot a part of my question. The code in question was building up a list, and he said:
Prefer foldr over foldl when possible, because it saves you a reverse at the end in cases where you're building up a list by appending elements during the fold.
As in, for a trivial example:
- val ls = [1, 2, 3];
val ls = [1,2,3] : int list
- val acc = (fn (x, xs) => x::xs);
val acc = fn : 'a * 'a list -> 'a list
- foldl acc [] ls;
val it = [3,2,1] : int list
- foldr acc [] ls;
val it = [1,2,3] : int list
The O(n) save of a reverse is probably more important than the other differences between foldl and foldr mentioned in answers to this question.
I am just starting to learn SML and having issues with my code. I want to compare an int with List of ints and return a list of numbers less than my int
fun less(e, L): L =
if L = [] then []
else (hd[L] < e :: less tl(hd))
I want to return a list of all numbers less than e by comparing it to the list L. What I'm I doing wrong?
hd[L] < e :: less tl(hd)
First of all less tl(hd) is the same as just less tl hd or (less tl) hd. Writing f g(x) does not mean "apply g to x and f to the result". For that you'd need to write f (g x). In general putting parentheses around atomic expressions won't change anything and by leaving out the space before the opening parentheses, you make the syntax look like something it's not, so you should avoid that.
Then tl hd simply doesn't make much sense as hd is a function and tl expects a list. You probably meant to apply tl to L, not to hd.
Then hd [L] takes the first element of the list [L]. [L] is a list with a single element: L. So writing hd [L] is the same thing as just writing L. You probably meant tot take the head of L. For that you'd just write hd L without the brackets.
Now the problem is that you're trying to prepend the result of (hd L) < e, which is a boolean, to the list. This will work (as in compile and run without error), but it will result in a list of booleans (which will contain a true for any element less than e and a false for any other element). That's not what you said you wanted. To get what you want, you should have an if which appends the head to the list if it is less than e and doesn't prepend anything when it's not.
Fixing these problems should make your code work as intended.
PS: Usually it's preferred to use pattern matching to find out whether a list is empty and to split a non-empty list into its head and tail. The functions hd and tl are best avoided in most circumstances and so is = []. However if you haven't covered pattern matching yet, this is fine for now.
PPS: You can do what you want much more easily and without recursion by using the filter function. But again: if you haven't covered that yet, your way is fine for now.
am i wrong is it that you didn't compare the elements. you only catered for the empty list.
something like
if e < hd L then e::less(e, (tl L))
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to tell if a list is infinite?
In Haskell, you can define an infinite list, for example [1..]. Is there a built-in function in Haskell to recognize whether a list has finite length? I don't imagine it is possible to write a user-supplied function to do this, but the internal representation of lists by Haskell may be able to support it. If not in standard Haskell, is there an extension providing such a feature?
No, this is not possible. It would be impossible to write such a function, because you can have lists whose finiteness might be unknown: consider a recursive loop generating a list of all the twin primes it can find. Or, to follow up on what Daniel Pratt mentioned in the comments, you could have a list of all the steps a universal Turing machine takes during its execution, ending the list when the machine halts. Then, you could simply check whether such a list is infinite, and solve the Halting problem!
The only question an implementation could answer is whether a list is cyclic: if one of its tail pointers points back to a previous cell of the list. However, this is implementation-specific (Haskell doesn't specify anything about how implementations must represent values), impure (different ways of writing the same list would give different answers), and even dependent on things like whether the list you pass in to such a function has been evaluated yet. Even then, it still wouldn't be able to distinguish finite lists from infinite lists in the general case!
(I mention this because, in many languages (such as members of the Lisp family), cyclic lists are the only kind of infinite lists; there's no way to express something like "a list of all integers". So, in those languages, you can check whether a list is finite or not.)
There isn't any way to test for finiteness of lists other than iterating over the list to search for the final [] in any implementation I'm aware of. And in general, it is impossible to tell whether a list is finite or infinite without actually going to look for the end (which of course means that every time you get an answer, that says finite).
You could write a wrapper type around list which keeps track of infiniteness, and limit yourself to "decidable" operations only (somehow similar to NonEmpty, which avoids empty lists):
import Control.Applicative
data List a = List (Maybe Int) [a]
infiniteList (List Nothing _) = true
infiniteList _ = false
emptyList = List (Just 0) []
singletonList x = List (Just 1) [x]
cycleList xs = List Nothing (cycle xs)
numbersFromList n = List Nothing [n..]
appendList (List sx xs) (List sy ys) = List ((+) <$> sx <*> sy) (xs ++ ys)
tailList (List s xs) = List (fmap pred s) (tail xs)
...
As ehird wrote, your only hope is in finding out whether a list is cyclic. A way of doing so is to use an extension to Haskell called "observable sharing". See for instance: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.31.4053
When talking about "internal representation of lists", from standpoint of Haskell implementation, there are no infinite lists. The "list" you ask about is actually a description of computational process, not a data object. No data object is infinite inside a computer. Such a thing simply does not exist.
As others have told you, internal list data might be cyclical, and implementation usually would be able to detect this, having a concept of pointer equality. But Haskell itself has no such concept.
Here's a Common Lisp function to detect the cyclicity of a list. cdr advances along a list by one notch, and cddr - by two. eq is a pointer equality predicate.
(defun is-cyclical (p)
(labels ((go (p q)
(if (not (null q))
(if (eq p q) t
(go (cdr p) (cddr q))))))
(go p (cdr p))))