ml datatype (with primitive functions) how to make?
i have this datatype
datatype e = X | Const of int | P 开发者_StackOverflow中文版of e*e | S of e*e | M of e*e | D of e*e;
and this procedure
val rec evl = fn (Const k)=>(fn x=>k)| X=> (fn x=>x)| P(e1,e2)=> (fn x=> (evl e1 x)+(evl e2 x))| S(e1,e2)=> (fn x=> (evl e1 x)-(evl e2 x))| M(e1,e2)=> (fn x=> (evl e1 x)*(evl e2 x))| D(e1,e2)=> (fn x=> (evl e1 x)/(evl e2 x));
how to expand this datatype and evl procedure to do:
-val addsub = evl( A( X(1),X(2),X(3), S( X(4),X(5) ) )) ; addsub(4,5,2,9,8) return it = 12 (4+5+2+(9-8))
P = +, S = -, M = * , D = / and not just for X(5), I need for X(n)...?
Some notes about your datatype and function:
- X is a redundant case, it has no meaning in context of arithmetic expression.
- You overused lamda functions, it makes your code so hard to understand.
S (subtract) and D (divide) are not commutative, it is a bad idea to do those operations on a list of arguments. I demonstrate how to do so with P (Plus) and M (Multiply):
datatype e2 = Const of int | P of e2 list | M of e2 list;
val rec evl2 =
fn Const k => k
| P es => List.foldl (fn (e, acc) => acc + (evl2 e)) 0 es
| M es => List.foldl (fn (e, acc) => acc * (evl2 e)) 1 es;
For example: evl2 (P [Const 3, Const 2, M [Const 3, Const 2, Const 1]])
would return 11
.
If you still want to do it with S and D, you can infer from the above code fragment.
精彩评论