I'm currently studying the language OCaml, and was solving an exercise problem when I came across a question that I can't seem to wrap my head around. Here's the question:
"Write a function differentiate : expression * string -> expression
that receives an algebraic equation and a string as an argument, and returns the differentiated version of the argument equation.
For example, diff (Add [Mult [Int 3 ; Exp("x", 2)] ; Mult [Int 6 ; Variable "x"], "x")
should produce the result:
Add [Mult [Int 6 ; Variable "x"] ; Int 6]
"
Here's the code that I wrote:
type expression =
| Int of int
| Variable of string
| Exponent of string * int
| Mult of expression list
| Add of expression list
let rec differentiate : expression * string -> expression
= fun (exp, x) ->
match exp with
| Int a -> Int 0
| Variable a -> if (a = x) then Int 1 else Variable a
| Exponent (a, b) -> if (a = x) then
match b with
| 2 -> Mult [Int 2; Variable a]
| _ -> Mult [Int b; Exponent (a, b - 1)]
else Int 0
| Mult [Int a; Int b] -> Const (a * b)
| Mult (Int a::[Variable b]) -> Mult (Int a::[differentiate (Variable b, x)])
| Mult (Int a::[Exponent (e1, e2)]) -> Mult (Int a::[differentiate (Exponent (e1, e2),
x)])
| Mult (Int a::[Mult (Int b :: l)]) -> Mult (Int (a * b) :: l)
| Add l -> match l with
| [] -> l
| hd::tl -> Add ((differentiate (hd, x)) :: tl)
;;
My algorithm is basically performing rigorous pattern matching. More specifically, for Mult
, the first element is always an integer, so I performed pattern matching on the second element. For Add
, my plan was to write the function so that it performs the function differentiate
on each element. Here are the specific problems I would like to ask about.
This code actually gives me an error on the
Add l
portion of pattern matching. The error message states:Error: This expression has type (expression list) but an expression was expected of type (expression).
As far as my understanding reaches, I am certain thatAdd l
is anexpression
type, not anexpression list
type. Why is this error message produced?I am not sure how to perform recursion in this specific example. My initial thought is that the function should only execute once each, otherwise the result would consist mainly of
Int 0
's orInt 1
's. Please correct me if I'm wrong.
Any feedback is greatly appreciated. Thank you!