Define the function add10, which takes an integer argument, adds 10 to it, and returns the result.
Define the function add20, which uses add10 to add 20 to a given integer. (add20 is not allowed to use “+".)
I am unsure if I am thinking too hard about this and there is a simpler solution like just adding another function he is not asking for, as he didn't specify whether I could or couldn't but only need to use the add10 and add20 functions alone, but I cannot figure out how to add the 20 without an addition sign to the outcome of add10.
Whenever I use just the add20
function it only whatever integer following it by 2.
Code and output as follows:
> let add10 x = x + 10;;
val add10 : x:int -> int
> add10 2;;
val it : int = 12
> let add20 add10 = add10 * 2;;
val add20 : add10:int -> int
> add20 3;;
val it : int = 6
> let j = 2 |> add10 |> add20;;
val j : int = 24
> let add20 add10 = add10 * 2;;
In this declaration, you are saying that add20
is a function which takes a parameter named add10
, and returns the value add10 * 2
. If you used a different name for the parameter, perhaps it would be clearer that this function simply multiplies its argument by 2:
> let add20 x = x * 2;;
> add20 33;;
val it : int = 66
The fact that the parameter is named add10
does not mean you are using the function add10
which has the same name; note from the type signature add20 : add10:int -> int
that the parameter add10
is expected to be an int
, not a function.
You seem to have come up with the basic idea of how to solve this problem, which is that the add20
function should work by doing add10
twice. The problem is that add10 * 2
does not mean "do the function add10
twice" , it means "multiply the number add10
by 2" , which is not what you intended.
What you really want to do is call the function twice , where the output of the first call is used as the input to the second call. You already seem to be aware of the pipe forwards operator |>
, so you could use this:
> let add20 x = x |> add10 |> add10;;
> add20 33;;
val it : int = 53
Or if you look at it another way, what you want is to take the function add10
and compose it with itself to define a new function. If you are familiar with the function composition operator >>
, you can write:
> let add20 = add10 >> add10;;
> add20 55;;
val it : int = 75
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.