Reputation: 91
I have recently been teaching myself Haskell, and one of my exercises was to implement a function that takes two functions as arguments and passes number 3 to the first function and the result to the second function. I have more experience with racket. The function that i created for racket is
(define (nestfun3 function function2)
(function2 (function 3)))
I'm trying to replicate this function in racket. i know that high order functions with only one function as argument can be like
twice function = function . function
How can I pass two functions? I tried
twice function = function . function
three function = function . twice
Upvotes: 2
Views: 540
Reputation: 52300
the direct translation would be:
apply3 :: Num a => (a -> b) -> (b -> c) -> c
apply3 f g = g (f 3)
remember: you don't want to just compose functions - you want to first apply 3
and then apply the result to the other function
sorry for the mixing ... this should work now:
λ> let f = (+1)
λ> let g = (*2)
λ> apply3 f g
8
λ> apply3 g f
7
in case you wondered - you don't have to actually start with the signature (although it's good practice to add it) - if you do this in ghci:
λ> let apply3 f g = g (f 3)
λ> :t apply3
apply3 :: Num a => (a -> t1) -> (t1 -> t) -> t
it will give it do you (or you can use ghc-mod or whatever) - I actually just renamed the type-parameters (those t
are ugly)
This way it should look very similar to what you did in Scheme
of course you might want to make sure not to swap functions while renaming :|
Upvotes: 5