1

I am trying to write a tail-recursive function in Standard ML to find the length of a list; so, for example, len([1,2,3,4,5]) should be 5.

I was able to do it in Scheme no problem:

(define (len1 lis sofar)
 (if
  (null? lis) sofar
  (len1 (cdr lis) (+ sofar 1))))

(define (len lis)
 (len1 lis 0))

(len (list 2 3 4 5 6 7)) = 6

But I can't seem to get it in SML. Here is what I have so far:

fun len [] = raise Fail "len: empty list"
 | len [x] = (x,x)
 | len (x::xs) =

or

len1([]:list, curLen:int) =  []null? then curLen | len1(tl[], curLen+1);

len([]) =  len1([], 0);
2
  • correction: ignore the first 3 lines listed under Sceme. They were an attempt on SML. Commented Mar 16, 2015 at 7:39
  • 3
    If you were able to do it in Scheme, then I can only presume you don't know the syntax of SML, in which case all you have to do it read a tutorial, like this one: homepages.inf.ed.ac.uk/stg/NOTES/node2.html. Commented Mar 16, 2015 at 10:17

1 Answer 1

1

In Standard ML, you can use pattern-matching instead of an explicit null? check.

fun length lst = let
    fun recur [] acc = acc
           (* we don't care about the value of the element *)
      | recur (_::rest) acc = recur rest (1 + acc)
  in recur lst 0
end

Trying it out in the REPL gives you the expected result.

Standard ML of New Jersey v110.76 [built: Thu Feb 19 00:37:13 2015]
- fun length lst = let
    fun recur [] acc = acc
           (* we don't care about the value of the element *)
      | recur (_::rest) acc = recur rest (1 + acc)
  in recur lst 0
end ;;
- length [] ;;
= val it = 0 : int
- length [1, 2, 3] ;;
= val it = 3 : int
- 

Agreed with the commenter to the OP, by the way. You managed fine in Scheme, which means you're probably having a bit of trouble with SML syntax. I suggest the appropriate Learn X in Y page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.