1
votes

I'm studying OCaml right now, and after I do this,

type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list

let rec diff : aexp * string -> aexp
=fun (aexp,x) -> match aexp with
|Const a -> Const 0
|Var "x" -> Const 1
|Power ("x", a) -> (match a with
 |2 -> Times[Const 2; Var "x"]
 |1 -> Const 1
 |0 -> Const 0
 |_ -> Times[Const a; Power ("x", a-1)])
|Times [l] -> (match l with
 |h::t -> (match t with
  |Var "x" -> h
  |Power ("x",a) -> Times [Times [h;Const a];diff(Power ("x",a),x)]))

I get an error:

File "", line 11, characters 3-5:

Error: The variant type aexp has no constructor ::

I learned that :: is concatenation of single element to a list or another element of a list.

It worked with my other codes that used list.

Why isn't it working here?

1

1 Answers

0
votes

Your pattern Times [l] matches a node Times with exactly one element named l. You wanted to write Times l, that matches a node Times with a list of any number of elements, bound to l in the body of the clause.

Note that in OCaml you can use nested pattern-matching, such as:

| Times (Var "x" :: _) -> h
| Times (Power ("x",a) :: _ ) -> ...
| ...