Take the 2-minute tour ×

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?

share|improve this question

2 Answers 2


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.

share|improve this answer

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))

share|improve this answer

Your Answer


