Reputation: 1113
I'm trying to implement a function, say f1, and I'm using previously defined function,say f2, to implement f1. f2 has multiple input like "f2 input1 input2 input3...". f1 return W.L.O.G input2 of f2. How can I correctly make the compiler know that I want f2 to accept the output of f1 as its input2 when using |> as in this statement: "f1 arg1 arg2... |> f2 input1 _ input3..."? If you look at my codes, the split function takes a list then an integer, but I want to give this function an list input using |>. The compiler gives error on "split e" in my function slice. It is expecting a list and not the number "e" when we do "l |> (split e)". You see that the function slice that I define doesn't follow the order of its arguments as required by the exercises. I did it so that I can use |> again to give slice a list input in another function f3 that uses the slice function. I'm wondering if this is necessary?
This is question 18 from this website for Ocaml exercises: "Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 0 (this is the way the List module numbers elements)."
(*Question 17*)
let split (l: 'a list) (m : int) =
let rec helper ll mm acc=
match ll with
|[]-> (acc,[])
|q::w -> if mm=m then ((acc@[q]),w) else helper w (mm+1) (acc@[q])
in helper l 1 []
(*Question 18 *)
let slice (b : int) (e :int) (l :'a list) =
let k=(fst (l |> (split e)) |> (split b)) in
(match snd k with
|[]->fst k
|a::_ -> (fst k)@[a])
Here is how slice should work:
slice ["a";"b";"c";"d";"e";"f";"g";"h";"i";"j"] 2 6;;
Upvotes: 0
Views: 415
Reputation: 66823
You could use various tricky higher-level functions to reorder the parameters of your second function, but in my opinion the thing to do is just to bite the bullet and use let
. The use of |>
is not mandatory when composing functions!
Instead of this:
f x |> g
You can say this:
let r = f x in
g r
So for your case you can say:
let r = f1 input1 input2 input3 in
f2 x r y
Upvotes: 1