Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the expression `ap zip tail` work

I wondered how to write f x = zip x (tail x) in point free. So I used the pointfree program and the result was f = ap zip tail. ap being a function from Control.Monad

I do not understand how the point free definition works. I hope I can figure it out if I can comprehend it from the perspective of types.

import Control.Monad (ap)
let f = ap zip tail
let g = ap zip
:info ap zip tail f g
ap :: Monad m => m (a -> b) -> m a -> m b
    -- Defined in `Control.Monad'
zip :: [a] -> [b] -> [(a, b)]   -- Defined in `GHC.List'
tail :: [a] -> [a]      -- Defined in `GHC.List'
f :: [b] -> [(b, b)]    -- Defined at <interactive>:3:5
g :: ([a] -> [b]) -> [a] -> [(a, b)]
    -- Defined at <interactive>:4:5

By looking at the expression ap zip tail I would think that zip is the first parameter of ap and tail is the second parameter of ap.

Monad m => m (a -> b) -> m a -> m b
           \--------/   \---/
              zip        tail

But this is not possible, because the types of zip and tail are completely different than what the function ap requires. Even with taking into consideration that the list is a monad of sorts.

like image 755
user7610 Avatar asked Oct 04 '13 13:10

user7610


1 Answers

So the type signature of ap is Monad m => m (a -> b) -> m a -> m b. You've given it zip and tail as arguments, so let's look at their type signatures.

Starting with tail :: [a] -> [a] ~ (->) [a] [a] (here ~ is the equality operator for types), if we compare this type against the type of the second argument for ap,

 (->) [x]  [x] ~ m a
((->) [x]) [x] ~ m a

we get a ~ [x] and m ~ ((->) [x]) ~ ((->) a). Already we can see that the monad we're in is (->) [x], not []. If we substitute what we can into the type signature of ap we get:

(((->) [x]) ([x] -> b)) -> (((->) [x]) [x]) -> (((->) [x]) b)

Since this is not very readable, it can more normally be written as

  ([x] -> ([x] -> b)) -> ([x] -> [x]) -> ([x] -> b)
~ ([x] ->  [x] -> b ) -> ([x] -> [x]) -> ([x] -> b)

The type of zip is [x] -> [y] -> [(x, y)]. We can already see that this lines up with the first argument to ap where

[x]         ~    [x]   
[y]         ~    [x]   
[(x, y)]    ~    b

Here I've listed the types vertically so that you can easily see which types line up. So obviously x ~ x, y ~ x, and [(x, y)] ~ [(x, x)] ~ b, so we can finish substituting b ~ [(x, x)] into ap's type signature and get

([x] -> [x] -> [(x, x)]) -> ([x] -> [x]) -> ([x] -> [(x, x)])
--   zip                        tail        ( ap  zip  tail )
--                                            ap  zip  tail u = zip u (tail u)

I hope that clears things up for you.

EDIT: As danvari pointed out in the comments, the monad (->) a is sometimes called the reader monad.

like image 140
bheklilr Avatar answered Oct 03 '22 06:10

bheklilr