passing a function with an arbitrary amount of parameters - function

I've recently been learning haskell from this awesome site, and I just learned about passing functions as parameters in the Higher Order Functions chapter. I can see how passing functions as parameters can be extremely useful, but from my current(lowley) understanding you need to specify the amount of parameters in this function, which can be quite limited given this function:
--takes a function and returns a function that has flipped arguments
flip' :: (a -> b -> c) -> (b -> a -> c) --very limited
flip' f = g
where g x y = f y x
useful, but only to the point of functions taking two parameters, is there a way to write a function definition that accepts functions with an arbitrary amount of parameters? My guess would have to be some sort of parameter list, but I can't seem to find any information on it. Thanks!

Actually flip works with functions with more than two parameters, but might not be exactly what you need:
Prelude> :t (,,,)
(,,,) :: a -> b -> c -> d -> (a, b, c, d)
Prelude> :t flip (,,,)
flip (,,,) :: b -> a -> c -> d -> (a, b, c, d)
since
(,,,) :: a -> b -> c -> d -> (a, b, c, d)
is
(,,,) :: a -> (b -> (c -> (d -> (a, b, c, d))))
the first two parameters get flipped. Here a is a, b is b, but c is c -> d -> (a, b, c, d).
And then again, what do you expect to achieve by flipping a 3 parameter function like in this example?
EDIT: And also, there are vararg functions - one example is printf. This Haskell.org page is pretty nice. In short, some typeclass magic could be used to achieve this effect.

Related

currying in haskell when the uncurried form is known

I've been learning currying in Haskell and now trying to write the Haskell type signature of a function in curried form, whose uncurried form has an argument pair of type (x, y) and a value of type x as its result. I think the correct approach would be f :: (y,x) -> x, but I'm not sure. Is it correct, and if not, why?
You can let ghci do this for you.
> f = undefined :: (a, b) -> c
> :t curry f
curry f :: a -> b -> c
You can uncurry the result to get back the original type.
> :t uncurry (curry f)
uncurry (curry f) :: (a, b) -> c
The actual implementation of curry is, perhaps, more enlightening.
curry :: ((a, b) -> c) -> a -> b -> c
curry f = \x -> \y -> f (x, y)
If f expects a tuple, then curry f simply packages its two arguments into a tuple to pass to f.
Examples are hard to come by, as functions in Haskell are usually fully curried already. But we can explicitly uncurry a binary operator to construct an example.
> (+) 3 5
8
> f = uncurry (+)
> f (3, 5)
8
> (curry f) 3 5
8
As an aside, the type you suggested is what you would get by inserting a call to flip between currying and uncurrying a function:
> :t uncurry . flip . curry
uncurry . flip . curry :: ((b, a) -> c) -> (a, b) -> c
To see this in action, you'd have to pick a non-commutative operator, like (++).
> strconcat = uncurry (++)
> strconcat ("foo", "bar")
"foobar"
> (uncurry . flip . curry) strconcat ("foo", "bar")
"barfoo"
Just swapping the elements of the tuple is not currying. You have to get rid of the tuple altogether. You can do that by taking the first element of the tuple as argument and returning a function which takes the second element of the tuple and finally returns the result type. In your case the type would be f :: x -> (y -> x), these parenthesis are redundant, it is the same as f :: x -> y -> x. This is the curried form.

How to Implement functions from type signatures?

I have the following two type signatures in Haskell:
foo :: (a -> (a,b)) -> a -> [b]
bar :: (a -> b) -> (a -> b -> c) -> a -> c
I want to write a concrete implementation of these two functions but I'm really struggling to understand where to start.
I understand that foo takes a function (a -> (a,b)) and returns a and a list containing b.
And bar takes a function (b -> c) which returns a function (a -> b -> c) which finally returns a and c.
Can anyone show me an example of a concrete implementation?
How do I know where to start with something like this and what goes on the left side of the definition?
You have some misunderstandings there:
I understand that foo takes a function (a -> (a,b)) and returns a and a list containing b.
No, it doesn't return a. It expects it as another argument, in addition to that function.
And bar takes a function (b -> c) which returns a function (a -> b -> c) which finally returns a and c.
Same here. Given g :: a -> b, bar returns a function bar g :: (a -> b -> c) -> a -> c. This function, in turn, given a function h :: (a -> b -> c), returns a function of type a -> c. And so it goes.
It's just like playing with pieces of a puzzle:
foo :: (a -> (a,b)) -> a -> [b]
-- g :: a -> (a,b)
-- x :: a
-- g x :: (a,b)
foo g x = [b] where
(a,b) = g x
bar :: (a -> b) -> (a -> b -> c) -> a -> c
-- g :: a -> b
-- x :: a
-- g x :: b
-- h :: a -> b -> c
-- h x :: b -> c
-- h x (g x) :: c
bar g h x = c where
c = ....
There's not much free choice for us here. Although, there are more ways to get more values of type b, for foo. Instead of ignoring that a in (a,b) = g x, we can use it in more applications of g, so there actually are many more possibilities there, like
foo2 :: (a -> (a,b)) -> a -> [b]
foo2 g x = [b1,b2] where
(a1,b1) = g x
(a2,b2) = g a1
and many more. Still, the types guide the possible implementations. foo can even make use of foo in its implementation, according to the types:
foo3 :: (a -> (a,b)) -> a -> [b]
foo3 g x = b : bs where
(a,b) = g x
bs = ...
So now, with this implementation, the previous two become its special cases: foo g x === take 1 (foo3 g x) and foo2 g x === take 2 (foo3 g x). Having the most general definition is probably best.
In addition to #will-nes's answer, it will be useful to treat (->) as a right-associative infix operator. So something like f: a -> b -> c is the same as f: a -> (b -> c). So this is saying f is a function that takes a value of type a and returns you a value of type b -> c, which is, another function, one that takes a value of type b and returns you a value of type c.
So the types in your example can be re-written as follows
foo :: (a -> (a,b)) -> (a -> [b])
bar :: (a -> b) -> ((a -> (b -> c)) -> (a -> c))
Similarly, you can think of arguments to a function in pieces as well, as being left-associative (like + and -), though there's no explicit operator in this case. foo a b c d e is the same as ((((foo a) b) c) d) e. For example, let's say we have a function f: Int -> Int -> Int (which is the same as f: Int -> (Int -> Int)). You don't have to provide both arguments at once. So you can write g = f 1, which has the type (Int -> Int). And then you can provide an argument to g, like g 2, which has the type Int. f 1 2 and let g = f 1 in g 2 are more or less the same. Here's a more concrete example of how this works:
Prelude> f = (+)
Prelude> g = f 1
Prelude> g 2
3
Prelude> :t f
f :: Num a => a -> a -> a
Prelude> :t g
g :: Num a => a -> a
Prelude> :t g 2
g 2 :: Num a => a
In #will-nes's sample implementation examples, he defines the functions with all of the arguments up front, but you don't have to think of them that way. Just think of f: a -> b -> c as taking a value of type a and returning another function. While most of the methods you encounter will use all of their arguments up-front, there might be cases in which you don't want to do that. Here's an example:
veryExpensive :: A -> B
unstagedFun :: A -> (B -> C) -> C
unstagedFun a f = f (veryExpensive a)
stagedFun :: A -> (B -> C) -> C
stagedFun a = let b = veryExpensive a in \f -> f b
(You can also rewrite the latter as let b = veryExpensive a in ($ b))
Of course, with compiler optimizations, I wouldn't be surprised if the unstaged version staged automatically, but hopefully this offers some motivation for thinking of functions as not having multiple arguments, but rather, as a single argument, but they may return other functions that may themselves return functions (but also only take a single argument).

Use of function application operator in Haskell

What does the following expression means in haskell?
($ 3)
ghci shows the following type
($ 3) :: Num a => (a -> b) -> b.
($ 3) is a section, and is equivalent to \f -> f 3, which takes a function argument and applies it to 3.
If we considered 3 to be an integer, we would have that the type of f is Int -> b (for any b), so the type of ($ 3) would be (Int -> b) -> b.
Things in Haskell are a bit more complex, since 3 can be of any numeric type, so we don't really need f :: Int -> b, it's enough if f :: a -> b where a is a numeric type.
Hence we get ($ 3) :: Num a => (a -> b) -> b.
(# x) for any operator # is equivalent to \a -> a # x; so ($ 3) is equivalent to \f -> f $ 3, i.e. a function that applies any function you pass it to 3. This syntax is called "sections".
> let f = ($ 3)
> f show
"3"
> f square
9
Another way to look at it is
($) :: (a -> b) -> a -> b
3 :: Num a => a
and when you "insert 3" in the ($) it will become
($ 3) :: Num a => (a -> b) -> b.
due to that you no longer need to supply the a, but the function you need to supply is now restricted to num, since the 3 can be any numeric type.
This is at least how I look at functions in Haskell, like substitution in algebra.

Haskell - apply tuple of functions to tuple of values?

I have a tuple of values representing some state, and want to translate it by an addition (shift). My values are a longer version of ( Int, [Int], Int), and I want something conceptually (but not literally) like this:
shift n = ??? (+n) (id, map, id) -- simple(?)
which would be equivalent to:
shift n (a, b, c) = (a+n, map (+n) b, c+n)
I am happy to just go with this explicit function usage, but wondered it there was a more idiomatic point-free version using Applicative or Arrows or ..., or if they would just end-up obfuscating things. I thought that the point-free version shows the basic structure of the operation more clearly.
You can just write
shift n (a,b,c) = (a+n, map (+n) b, c+n)
Or define new combinators similar to Arrow's (***) and (&&&),
prod3 (f,g,h) (a,b,c) = (f a, g b, h c) -- cf. (***)
call3 (f,g,h) x = (f x, g x, h x) -- cf. (&&&)
ap3 f (a,b,c) = (f a, f b, f c)
uncurry3 f (a,b,c) = f a b c
and then call
prod3 ( (+n), map (+n), (+n) ) (a,b,c)
or even (with appropriately set operator precedences)
ap3 ($ (+n)) (id, map, id) `prod3` (a,b,c)
Or, if you'd write your triples as nested pairs, you could use
Prelude Control.Arrow> ( (+5) *** map (+5) *** (+5) ) (1,([2,3],4))
(6,([7,8],9))
So for nested pairs,
shift' :: (Num b) => b -> (b, ([b], b)) -> (b, ([b], b))
shift' n = ( (+n) *** map (+n) *** (+n) )
(see also Multiple folds in one pass using generic tuple function)
With the DeriveFunctor language extension you can write
data MyState a = MyState a [a] a
deriving (Functor)
The derived instance looks like
instance Functor MyState where
fmap f (MyState a bs c) = MyState (f a) (map f bs) (f c)
Now you can define
shift :: MyState Int -> MyState Int
shift n = fmap (+n)
(You say your tuple is even longer than (Int, [Int], Int), so you may want to define your state type using record syntax.)
Applying a list of functions to a list of values is simply
zipWith ($)
Since tuples of different sizes are each their own type, you will have to write a function explicitly for 3-tuples. A general function to apply a 3-tuple of functions to a 3-tuple of values is
apply (f, g, h) (a, b, c) = (f a, g b, h c)
You have to explicitly write each function application because tuples don't have the recursive property of lists.

Composing two error-raising functions in Haskell

The problem I have been given says this:
In a similar way to mapMaybe, define
the function:
composeMaybe :: (a->Maybe b) -> (b -> Maybe c) -> (a-> Maybe c)
which composes two error-raising functions.
The type Maybe a and the function mapMaybe are coded like this:
data Maybe a = Nothing | Just a
mapMaybe g Nothing = Nothing
mapMaybe g (Just x) = Just (g x)
I tried using composition like this:
composeMaybe f g = f.g
But it does not compile.
Could anyone point me in the right direction?
The tool you are looking for already exists. There are two Kleisli composition operators in Control.Monad.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
When m = Maybe, the implementation of composeMaybe becomes apparent:
composeMaybe = (>=>)
Looking at the definition of (>=>),
f >=> g = \x -> f x >>= g
which you can inline if you want to think about it in your own terms as
composeMaybe f g x = f x >>= g
or which could be written in do-sugar as:
composeMaybe f g x = do
y <- f x
g y
In general, I'd just stick to using (>=>), which has nice theoretical reasons for existing, because it provides the cleanest way to state the monad laws.
First of all: if anything it should be g.f, not f.g because you want a function which takes the same argument as f and gives the same return value as g. However that doesn't work because the return type of f does not equal the argument type of g (the return type of f has a Maybe in it and the argument type of g does not).
So what you need to do is: Define a function which takes a Maybe b as an argument. If that argument is Nothing, it should return Nothing. If the argument is Just b, it should return g b. composeMaybe should return the composition of the function with f.
Here is an excellent tutorial about Haskell monads (and especially the Maybe monad, which is used in the first examples).
composeMaybe :: (a -> Maybe b)
-> (b -> Maybe c)
-> (a -> Maybe c)
composeMaybe f g = \x ->
Since g takes an argument of type b, but f produces a value of type Maybe b, you have to pattern match on the result of f x if you want to pass that result to g.
case f x of
Nothing -> ...
Just y -> ...
A very similar function already exists — the monadic bind operator, >>=. Its type (for the Maybe monad) is Maybe a -> (a -> Maybe b) -> Maybe b, and it's used like this:
Just 100 >>= \n -> Just (show n) -- gives Just "100"
It's not exactly the same as your composeMaybe function, which takes a function returning a Maybe instead of a direct Maybe value for its first argument. But you can write your composeMaybe function very simply with this operator — it's almost as simple as the definition of the normal compose function, (.) f g x = f (g x).
Notice how close the types of composeMaybe's arguments are to what the monadic bind operator wants for its latter argument:
ghci> :t (>>=)
(>>=) :: (Monad m) => m a -> (a -> m b) -> m b
The order of f and g is backward for composition, so how about a better name?
thenMaybe :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c)
thenMaybe f g = (>>= g) . (>>= f) . return
Given the following definitions
times3 x = Just $ x * 3
saferecip x
| x == 0 = Nothing
| otherwise = Just $ 1 / x
one can, for example,
ghci> saferecip `thenMaybe` times3 $ 4
Just 0.75
ghci> saferecip `thenMaybe` times3 $ 8
Just 0.375
ghci> saferecip `thenMaybe` times3 $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 1
Just 0.3333333333333333