Adam Sh
Adam Sh

Reputation: 8577

SML - unbound variable or constructor

I have the next code:

datatype expr = K of string| Number2 of expr * (expr list);
datatype number = Number1 of string | Number3 of int;
 fun append (nil, l2) = l2 
  | append (x::xs, l2) = x::append(xs, l2);
 fun map [] = []
    | map (h::t) = (What h)::(map t);
fun What (K x) = [Number1(x)]
    |What (Number2 (t,[])) = Number3(0)::What(t)
    |What (Number2 (y,a::b)) =  append(What(a), map(b));

It doesn't recognize the function "What".(unbound variable or constructor). How can I fix it, that it will know the function "What"?

Thanks.

Upvotes: 7

Views: 15678

Answers (2)

Nicholas Wilson
Nicholas Wilson

Reputation: 9696

You have to use and for mutual recursion. You have some other problems though in your code. What is clearly an expr -> number list, which means map must be expr list -> (number list) list, so in your final line you're trying to append a number list list to a number list. It's not at all clear what the code is meant to be doing though, so you might have to work out your intended logic on your own. There doesn't look to be any obvious way to write a function with the required type.

Upvotes: 3

Michael J. Barber
Michael J. Barber

Reputation: 25052

Declarations in SML work from top to bottom, so map doesn't see What. Switching the order won't help, as then What wouldn't see map, giving the same error. Instead, you need to declare the mutually recursive functions simultaneously using and:

fun map [] = []
  | map (h::t) = (What h)::(map t)
and What (K x) = [Number1(x)]
  | What (Number2 (t,[])) = Number3(0)::What(t)
  | What (Number2 (y,a::b)) =  append(What(a), map(b))

Upvotes: 10

Related Questions