Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing pattern matching and currying in OCaml

Tags:

ocaml

In SML, it's common and easy to define a function using both currying and pattern matching. Here's a simple example:

fun zip [] _ = []
  | zip _ [] = []
  | zip (x::xs) (y::ys) = (x,y)::(zip xs ys)

Ignoring library functions, what's the best way to port this to OCaml? As far as I can tell, there is no easy way to declare a function using both currying and pattern matching.

like image 663
James Koppel Avatar asked Sep 11 '11 02:09

James Koppel


1 Answers

I would say it's best to just use a match expression.

let rec zip xs ys = 
    match xs, ys with
    | [], _
    | _, [] -> []
    | x :: xs, y :: ys -> (x, y) :: zip xs ys

If you're set on not using match, it's a bit convoluted, but you can do this.

let rec zip = function
    | [] -> (fun _ -> [])
    | x :: xs ->
        function 
        | [] -> []
        | y :: ys -> (x, y) :: zip xs ys
like image 66
jonathan Avatar answered Nov 08 '22 15:11

jonathan