Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SML - unbound variable or constructor

Tags:

sml

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.

like image 885
Adam Sh Avatar asked Nov 04 '11 13:11

Adam Sh


2 Answers

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))
like image 106
Michael J. Barber Avatar answered Nov 20 '22 15:11

Michael J. Barber


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.

like image 22
Nicholas Wilson Avatar answered Nov 20 '22 14:11

Nicholas Wilson