Peter Hwang
Peter Hwang

Reputation: 991

ocaml implementation of pipe

I am trying to implement something like a pipe function.

Input: a list of functions

Output: a function

Example:

# pipe [(fun y -> y+5);(fun y -> y*3)] 1 = 18
# pipe [(fun z -> z*3);(fun z -> z+5)] 1 = 8

My problem:

A helper function composite takes two arguments, which are a function f and a list of function l. If the list is empty, it returns the function f. If it is not, f will be an argument of the head of list g. However, I got a syntax error. I don't figure out what's going on. Has anyone found an error?

let pipe l =
  let composite f l = match l with
      []->f
    | g::gs -> (fun h -> (g -> f)) in
  List.fold_left composite (fun x -> x) l

Upvotes: 0

Views: 874

Answers (1)

gasche
gasche

Reputation: 31459

(fun h -> (g -> f)) is not syntactically correct, and I'm not sure what it is supposed to mean.

The pattern-matching of your composite function looks like what you would write for a recursive function, but then you're trying to define it non-recursively for use with fold_left. Either way would be good, but you need to make up your mind, because here you've a sad compromise that does not work.

Upvotes: 3

Related Questions