rubyquartz
rubyquartz

Reputation: 321

OCaml Understanding Functions and Partial Applications

I am writing a form of form of transform in OCaml that takes in a function and also accepts a list to transform. I understand something is wrong with my pattern matching in terms of type-checking, as it will not compile and claims the types do not match but I am not sure what exactly is wrong with my cases. I receive an actual declaration error underlining the name of the function when I attempt to compile.

 let rec convert (fun: 'b -> 'c option) (l: 'b list) : 'c list =
 begin match l with
| [] -> []
| h::tl -> if f h = Some h then h :: convert f tl
         else convert f tl

end

I wrote the following test, which should pass in order to ensure the function works properly.

let test () : bool =
let f = func x -> if x > 3 then Some (x + 1) else None in
convert f [-1; 3; 4] = [5]
;; run_test "Add one" test

I am pretty confident the error is somewhere in my second pattern match.

Upvotes: 0

Views: 426

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

  1. You should provide the exact error message in the future when asking about a compilation error (as well as the position the compiler complains about).

  2. In h :: convert f tl, convert f tl is 'c list, but h is 'b, so you can't combine them like this. Neither does f h = Some h make sense: f h is 'c option and Some h is 'b option. You probably want to match f h instead:

    | h::tl -> match f h with
                 | Some h1 -> ...
                 | None -> ...
    

Upvotes: 2

Related Questions