h2oBoost
h2oBoost

Reputation: 13

SML getting an unbound variable or constructor error when everything seems right

I'm trying to figure out mutual recursion. I have this code:

fun take(L)=
      if L=nil then nil
      else hd(L) :: skip(tl(L))
AND
fun skip(L)=
      if L=nil then nil
      else take(tl(L));

but it gives me these errors:

stdIn:54.14-54.18 Error: unbound variable or constructor: skip
stdIn:55.1-55.4 Error: unbound variable or constructor: AND

What am I doing wrong?

Upvotes: 1

Views: 979

Answers (1)

ruakh
ruakh

Reputation: 183201

Your immediate error is because Standard ML is case-sensitive, and all of its reserved words are in lowercase; so you need to write and rather than AND.

Additionally, fun introduces an entire declaration, not an individual binding, meaning that you need to remove the extra fun after and.

Lastly, your functions currently require the list to have an equality type (such as int list or string list), which may not be a deal-breaker, but given what the functions actually do, there's really no reason they can't support non-equality types such as real list. To achieve that, you should match the parameter against the pattern nil, instead of testing whether the parameter equals nil. (More generally, you should use pattern-matching in more places; you have no reason to call hd and tl.)

Putting it together:

fun take nil = nil
  | take (h::t) = h :: skip t
and skip nil = nil
  | skip (h::t) = take t

Upvotes: 1

Related Questions