Reputation: 25
How do I pass a function result as a parameter to another function?
Example:
let function a b = a/b;;
let anotherFunction p t = p + t;;
function 10 5;;
Can I pass the result from function (2) to a parameter - let's say t in anotherFunction?¨
Upvotes: 1
Views: 391
Reputation: 36680
Late addition, but note also that for complex expressions, you may wish to use a local binding via the let ... in ...
construct.
# let function1 a b = a / b
let function2 p t = p + t;;
val function1 : int -> int -> int = <fun>
val function2 : int -> int -> int = <fun>
# let result = function1 5 2 in
function2 15 result;;
- : int = 17
Where the first expression is passed as the last argument of the second function, we can also use the |>
or @@
operators.
# function1 5 2 |> function2 15;;
- : int = 17
# function2 15 @@ function1 5 2;;
- : int = 17
It may be difficult to see from such a simple example, how these would be useful, but when chaining many operations together they can improve code readability substantially. Consider multiple operations on a list.
# let lst = [1;2;3;4;5;6] in
List.(
map (fun x -> x * 2) (filter (fun x -> x mod 2 = 0) (map (fun x -> x + 1) lst))
);;
- : int list = [4; 8; 12]
Or:
# let lst = [1;2;3;4;5;6] in
List.(
lst
|> map (fun x -> x + 1)
|> filter (fun x -> x mod 2 = 0)
|> map (fun x -> x * 2)
);;
- : int list = [4; 8; 12]
Or:
# let lst = [1;2;3;4;5;6] in
List.(
map (fun x -> x * 2)
@@ filter (fun x -> x mod 2 == 0)
@@ map (fun x -> x + 1)
@@ lst
);;
- : int list = [4; 8; 12]
I'm partial to the |>
solution as it not only reduces nested parentheses (and thus mental load) but it also puts the last operation last in the reading order.
Upvotes: 0
Reputation: 66823
You can't have a function named function
, which is a keyword in OCaml. So let's call it firstFunction
.
I think what you're asking for is this:
anotherFunction 13 (firstFunction 10 5)
Here's a toplevel session:
# let firstFunction a b = a / b;;
val firstFunction : int -> int -> int = <fun>
# let anotherFunction p t = p + t;;
val anotherFunction : int -> int -> int = <fun>
# anotherFunction 13 (firstFunction 10 5);;
- : int = 15
(For simple questions like this it might help to spend a little time typing expressions into the toplevel. It should start to make sense pretty quickly.)
Upvotes: 5