Nicholas Gyde
Nicholas Gyde

Reputation: 23

How can I make an anonymous function in SML that uses pattern matching (like a fun)?

I have a datatype:

datatype 'a tree = LEAF of 'a 
            | NODE of 'a tree * 'a tree;

I wish to make a function called maptree(f), which returns an anonymous function capable of enacting f element-wise on a tree. Why does the following not work?

fun maptree(f) = fn LEAF(a) => LEAF(f(a))
                  | NODE((b,c)) => NODE(f(b), f(c));

I get the error:

stdIn:56.7-56.65 Error: types of rules don't agree [circularity]
earlier rule(s): 'Z tree tree -> 'Y tree tree
this rule: 'Z tree -> 'Y tree
in rule:
NODE (b,c) => NODE (f b,f c)

Upvotes: 1

Views: 1481

Answers (1)

seanmcl
seanmcl

Reputation: 9944

f : 'a -> 'b

so you can't apply it to a tree. You probably wanted.

fun maptree f = fn LEAF a => LEAF (f a)
                 | NODE(b,c) => NODE (maptree f b, maptree f c);

Upvotes: 4

Related Questions