I need to write a pipe
function in OCaml such that pipe [f1;...;fn]
(where f1
,...,fn
are functions!) returns a function f
such that for any x, f x
computes fn(...(f2(f1 x)))
.
I need to write it using List.fold_left
and need to fill in the parameter of the function
let pipe fs =
let f a x = "fill in this part" in
let base = fun x ->x in
List.fold_left f base fs;;
I already filled in the base. If the first parameter to pipe is an empty list, it returns the second parameter. Ex: pipe [] 3 = 3. i know for the let f a x part I want to perform function x of the accumulated functions a. I'm just not sure how to write that. I wrote let f a x = x a but that gave me an error when i tested pipe [(fun x -> x+x); (fun x -> x + 3)] 3
it should run x+x on 3 then run x+3 on the result and give me 9 but it gave it a type error when i tried to use let f a x = x a for the fill in part
# let _ = pipe [(fun x -> x+x); (fun x -> x + 3)] 3;;
File "", line 1, characters 24-25:
Error: This expression has type 'a -> 'a
but an expression was expected of type int
What is the correct format to create a function that takes in 2 functions and runs them on each other. Ex: make a function that takes in functions a and b and runs b on the result of a.
let f a b x = b (a x)
. – Jeffrey Scofieldf
has to return a function. So it should return something that looks like this:fun z -> ...
. You need to figure out what the returned function should be doing with its argumentz
. – Jeffrey Scofield