first, this is my code :
module Problem1 = struct
type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let diff : aexp * string -> aexp
= fun (exp, var) ->
match exp with
|Const a -> Const 0
|Var x -> if x = var then Const 1 else Var x
|Power (s, i) ->
if s = var then Times[Const i;Power (s, i - 1)] else Power (s, i)
|Times l ->
match l with
|h::t -> Sum[Times[diff (h, var);t];diff (t, var)]
|Sum m ->
match m with
|h::t -> Sum[diff(h, var); diff(t, var)];;
end
The interpretor says,
Error: This variant pattern is expected to have type aexp list
The constructor Sum does not belong to type list
But I intended the symbol m to be an aexp list. Can't find what is wrong.
Actually your problem is simple and you would have seen it by using a tool that knows how to indent OCaml code ;-)
Look at how your last lines are indented with an OCaml indenter :
|Times l ->
match l with
|h::t -> Sum[Times[diff (h, var);t];diff (t, var)]
|Sum m ->
match m with
|h::t -> Sum[diff(h, var); diff(t, var)];;
Yes, that's right, since you created a new pattern matching in Times l
, Sum m
is included in it. You should write
|Times l -> begin
match l with
|h::t -> Sum[Times[diff (h, var);t];diff (t, var)]
end
|Sum m ->
match m with
|h::t -> Sum[diff(h, var); diff(t, var)];;
And it will work just fine.
By the way, you'll have another problem because you didn't write let rec diff ...
but let diff
and you're calling diff
recursively.