In ghci,
:t ((+).(+))
> ((+).(+)) :: (Num (a -> a), Num a) => a -> (a -> a) -> a -> a
but what is this thing? Can any one give me an example of the use of this please?
How can one composite 2 functions that take 2 parameters each?
for example, how does (map.map) :: (a -> b) -> [[a]] -> [[b]] work?
(^.^)
(-.-)
(+.+) (can't help making funny faces out of it. PS: I thought it means to tell the compiler how you feel today)
Num (a -> a) (or e.g. Eq (a -> a)) is basically an indicator for code that doesn't make any sense1, but the compiler nevertheless deduces a (nonsensical) type signature. Usually it turns up when you've forgotten to apply a function to some argument. In this case, obviously (+) needs a "plain number" argument to become a "simple function" to which you can post-compose another such function.
However, (a -> a) is sure enough a valid type of functions that you can also pass on, just not as numbers. For instance, map . (+) is a perfectly good combination:
Prelude> :t map . (+)
map . (+) :: Num b => b -> [b] -> [b]
Prelude> zipWith (map . (+)) [10,20,30] [[1,2],[3,4]]
[[11,12],[23,24]]
because map actually expects a function as its first argument. Similarly,
Prelude> zipWith (map . map) [(+10),(+20),(+30)] [[[1,2],[3,4]],[[5,6]]]
[[[11,12],[13,14]],[[25,26]]]
Here, the right map takes a simple function (like numerical increment) and returns the corresponding list-map function. That function is then fed to the left map resulting in a function that maps nested lists.
1Actually, you can force it to make sense by defining
instance (Num a) => Num (b -> a) where
fromInteger x = const $ fromInteger x
f + g = \x -> f x + g x
Personally, I'm not a fan of this. It confusing, for instance let a = 3 in 4 a produces 4 when most people would expect multiplication to 12.
That won't work. As ghci tells you, you should have an instance of Num (a -> a) in order to use that function, but a -> a obviously isn't a number.
This is because (+) assumes to get two numerical parameters, but with the composition you wrote you gave it a partially applied function instead, the a -> a mentioned in the computed type signature.
Usually, when composing functions which take more than one parameter, you partially apply them first in order to reduce them to functions which take just one parameter, e.g. (+1) . (*2) applied to 3 will result in (3 * 2) + 1 = 7
f . f can make sense for a binary function f; it entirely depends on the signature of f. The key is that partial application of the inner f to its first argument has to give something that is a valid input to the outer f.
For example, with map :: (a -> b) -> [a] -> [b], we can hand-unify map . map:
map :: (a -> b) -> [a] -> [b]
map :: (c -> d) -> [c] -> [d]
. :: (e -> f) -> (f -> g) -> (e -> g)
e === a -> b
f === [a] -> [b]
=== c -> d
c === [a]
d === [b]
g === [c] -> [d] === [[a]] -> [[b]]
map . map :: e -> g
:: (a -> b) -> [[a]] -> [[b]]
So, as expected, map . map takes a transformation a -> b and gives us a transformation from list-of-list-of-a to list-of-list-of-b. We can check this by hand-applying (map . map) f ll:
(map . map) f ll
= map (map f) ll
= map (\l -> map f l) ll
But if we try the same with (+) :: Num a => a -> a -> a, it all goes horribly wrong:
(+) :: Num a => a -> a -> a
(+) :: Num b => b -> b -> b
. :: (c -> d) -> (d -> e) -> (c -> e)
c === a
d === a -> a
=== b
e === b -> b === (a -> a) -> (a -> a)
(+) . (+) :: c -> e
:: (Num a, Num (a -> a)) => a -> (a -> a) -> (a -> a)
So, partial application of the inner + is giving a transformation a -> a, the outer + is then trying to add that transformation to another function which we are expected to supply. Since it doesn't make sense to add transformations, the overall (+) . (+) doesn't make sense either.
g . f means applying f first, then applying g to the result of f, in
other words, it can be rewritten as
\x -> g (f x)
Therefore,
((+) . (+))
can be rewritten as
\x -> (\y -> (x +) + y)
According to the type of (+), in the above lambda abstraction, x needs
having type Num a => a, y having type Num a => Num (a -> a), as inferred
by ghci
(Num a, Num (a -> a)) => a -> (a -> a) -> a -> a
So if we have made a -> a an instance of type class Num a, for example,
here is one way to achieve that
{-# LANGUAGE FlexibleInstances #-}
instance (Num a) => Num ((->) a a) where
a + b = \x -> a x + b x
a * b = \x -> a x * b x
a - b = \x -> a x - b x
negate a = \x -> negate $ a x
abs a = \x -> abs $ a x
signum a = \x -> signum $ a x
fromInteger n = \_x -> fromInteger n
we can use ((+) . (+)) like this
*Main> ((+) . (+)) 1 (+2) 3
9
Because ((+) . (+)) equals
\x -> \y -> (x +) + y
which means ((+) . (+)) 1 (+2) 3 equals
((1 + ) + (+ 2)) 3
according to the definition of (+) in the instance of (a -> a), ((1+) +
(+2)) equals
\x -> (1+x) + (x+2)
So ((1+) + (+2)) 3 equals (1+3) + (3+2), which is 9, as given by ghci.
map . map is similar, as indicated by its type, given by ghci:
(a -> b) -> [[a]] -> [[b]]
the first argument of that function should be a function of type a->b, the
second argument should be a nested list of type [[a]], and that composed
function map . map will apply the first argument to each element of each
list in its second argument, return a nested list of type [[b]]. For
example
*Main> (map . map) (+1) [[1,2], [3,4,5]]
[[2,3],[4,5,6]]
Related
Asking the GHC to print the type of "one" and "succ zero" (lambda calculus way of encoding numerals), I get two different types!
Shouldn't they be the same?
Can you also show me how to derive its type manually?
zero = \ f x -> x
one = \ f x -> f x
succ = \ n f x -> f (n (f x))
:t one -- (t1 -> t2) -> t1 -> t2
:t succ zero -- ((t1 -> t1) -> t2) -> (t1 -> t1) -> t2
So as was said in the comments, the correct definition is
zero f x = x
succ n f x = f (n f x)
"do one more f after n applications of f, starting with x."
Thus
one f x = succ zero f x = f (zero f x) = f x
two f x = succ one f x = f (one f x) = f (f x)
The types which get derived are more general initially,
zero :: t -> t1 -> t1 -- most general
one :: (t1 -> t ) -> t1 -> t -- less general
succ one :: (t2 -> t2) -> t2 -> t2 -- most specific
but it doesn't matter, they all match (unify) between themselves, and starting from two = succ one the type settles down into the most specific (b -> b) -> (b -> b).
You could also define
church :: Int -> (b -> b) -> b -> b -- is derived so by GHCi
church n f x = foldr ($) x (replicate n f)
= foldr (.) id (replicate n f) x
{- church n = foldr (.) id . replicate n -- (^ n) for functions -}
and have all types be exactly the same, as
church 0 :: (b -> b) -> b -> b
church 1 :: (b -> b) -> b -> b
church 2 :: (b -> b) -> b -> b
It really doesn't matter.
As to the type derivations, it comes down to just using the modus ponens / application rule,
f :: a -> b
x :: a
-------------
f x :: b
Just need to be careful renaming each type consistently so there's no type variable capture introduced at any step:
succ n f x = f (n f x)
x :: a
f :: t , t ~ ...
n :: t -> a -> b
f :: b -> c , t ~ b -> c
succ n f x :: c
succ :: (t -> a -> b) -> (b -> c) -> a -> c
:: ((b -> c) -> a -> b) -> (b -> c) -> a -> c
(because final result type produced by succ is the same as the final result type produced by f -- i.e. c), or as GHCi puts it,
succ :: ((t1 -> t) -> t2 -> t1) -> (t1 -> t) -> t2 -> t
-- b c a b b c a c
Firstly, you want zero to be same type as one. In your equation for zero, you don't use f on rhs of ->. So the compiler doesn't know what type to infer. In your equation for one, you want f x (its result) to be same type as x (the result from zero). But you're not getting that either. It's easiest to give signatures, but failing that use asTypeOf.
In the equation for succ, you want its result to be same type as f x, same type as x.
Can you also show me how to derive its type manually?
OK let's achieve the above using asTypeOf. Then you can use :t to find the types ...
zero = \ f x -> (x `asTypeOf` f x)
one = \ f x -> (f x `asTypeOf` x)
succ = \ n f x -> (f (n f x)
`asTypeOf` f x `asTypeOf` x)
(I've used the correct definition for succ, per #LambdaFairy.)
Note that Church numerals are framed in the untyped lambda calculus -- that's what wikipedia is showing. As you get into more exotic functions over them (like addition or predecessor), you'll find that Haskell is a typed lambda calculus, and GHC will barf/you'll hit the dreaded monomorphism restriction. Then asTypeOf can't help you; you must resort to type signatures (of higher-rank).
On my GHCi foldr and foldl have this signature:
Prelude> :t foldr
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
Prelude> :t foldl
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
What is the difference between the alternative type signature of fold, specifically t a part?
fr :: (a -> b -> b) -> b -> [a] -> b
fl :: (b -> a -> b) -> b -> [a] -> b
The type class Foldable defines a number of functions in addition to foldl.
class Foldable t where
foldMap :: Monoid m => t m -> m
foldr :: (a -> b -> b) -> b -> t a -> b
foldl :: (b -> a -> b) -> b -> t a -> b
-- ...
We can define an instance of Foldable for a type constructor t by defining at least foldMap or foldr for the type. (foldl has a default definition in terms of some of the others, so you get it for "free" as long as you supply the minimum definition).
instance Foldable [] where
foldr f b [] = b
foldr f b (x:xs) = f x : foldr f b xs
instance Foldable Maybe where
foldr f b Nothing = b
foldr f b (Just a) = f b a
The t in the type signature just means that as long as a type constructor has a Foldable instance for it defined, you can use foldl with a value of the appropriate type. For example:
Prelude> foldl (+) 0 [1,2,3]
6
Prelude> foldl (+) 0 []
0
Prelude> foldl (+) 0 Nothing
0
Prelude> foldl (+) 0 (Just 3)
3
In the first two cases, we use the [] instance because the arguments corresponding to t a are lists, meaning t is unified with [], written t ~ []. In the second two, we use the Maybe instance because the arguments corresponding to t a are Maybe values, so t ~ Maybe.
I can't understand way of working composition in haskell,
for example:
((.) . (+)) 3 (*2) 9 = 9 * 2 + 3 = 21
This answer is generated by ghci.
For me, it should be:
((.) . (+)) 3 (*2) 9 = (3+9) * 2
Similarily, I can't understand why type of ((.) . (+)) is Num c => c -> (a -> c) -> a -> c
Can you try to explain it me ?
In this expression, (.) is applied to two arguments, (.) again and (+). Let's take it one step at a time. First, partially apply (.) to (.). We'll write the type signatures down explicitly, using different type variables to distinguish between the two:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) :: (t -> u) -> (s -> t) -> s -> u
Now look at the type of (.) (.) (the partial application). (This is probably the trickiest step, due to the size of the type expressions involved. The next step is the same, but with simpler types.) The first argument, of type (b -> c), is unified with (t -> u) -> (s -> t) -> s -> u, meaning
b ~ t -> u
c ~ (s -> t) -> s -> u
When we do the partial application, we drop the first argument to (.) (since we've given it a value) and look at the type after replacing the remaining bs and cs with their new types.
(.) :: (b -> c) -> (a -> b ) -> a -> c
(.) (.) :: (a -> (t -> u)) -> a -> ((s -> t) -> s -> u)
Because -> is right-associative, we can drop some of the excess parentheses to get
(.) (.) :: (a -> t -> u) -> a -> (s -> t) -> s -> u
Now, we apply that to (+) :: Num v => v -> v -> v (again, using a new type variable for clarity). The first argument of (.) (.) has type a -> t -> u, which we need to unify with v -> v -> v. In other words, we'll replace all occurrences of a, t, and u in (.) (.)'s type with v
(.) (.) :: (a -> t -> u) -> a -> (s -> t) -> s -> u
(.) (.) (+) :: v -> (s -> v) -> s -> v
And as you can see (after we add the Num v constraint back), this is equivalent to the type you see:
-- v ~ c, s ~ a
Num v => v -> (s -> v) -> s -> v
Num c => c -> (a -> c) -> a -> c
As for the actual expression being evaluated,
((.) . (+)) 3 (*2) 9
keep in mind the definition of (.)
f . g = \x -> f (g x)
and work from left to right. First, (.) . (+) is applied to 3.
((.) . (+)) 3 == (.) ((+) 3)
== (.) (3 +)
This partial application of . is applied to (* 2):
(.) (3 +) (* 2) == (3 +) . (* 2)
== \x -> (3 +) ((* 2) x)
Finally, this function is applied to 9:
(\x -> (3 +) ((* 2) x)) 9 == (3 +) ((* 2) 9)
== (3 +) (9 * 2)
== 3 + 9 * 2
== 3 + 18
== 21
I'm trying to figure out how to negate the results of two parameter boolean function like not . any. I understand why it didn't work by breaking it down as shown below, but I'm not sure how to write a function that does this elegantly. I managed to do curry $ not . uncurry any
Prelude> :t not
not :: Bool -> Bool
Prelude> :t any
any :: Foldable t => (a -> Bool) -> t a -> Bool
Prelude> :t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
curry $ not . uncurry any
:: Foldable t => (a -> Bool) -> t a -> Bool
There is a standard point-free-ifier, available standalone or via lambdabot, which gives:
18:02 <dmwit> ?pl \f xs -> any (\x -> not (f x)) xs
18:02 <lambdabot> any . (not .)
18:04 <dmwit> ?pl \f xs -> not (any f xs)
18:04 <lambdabot> (not .) . any
There are many ways to spell this general operation.
Edit: Thanks to zudov for the following suggested extra text: You can also access pointfree tool by installing pointfree or using one of web interfaces (e.g. http://pointfree.io).
Define
result = (.)
argument = flip (.)
Then you want
(result.result) not any
i.e., negating the second result of any.
(It's also
argument (result not) all
i.e., negate the predicate then pass it into all).
See http://conal.net/blog/posts/semantic-editor-combinators
(.:) :: (r -> z) -> (a -> b -> r) -> a -> b -> z
(f .: g) x y = f (g x y)
foo :: (a -> Bool) -> [a] -> Bool
foo = not .: any
.: is also available in Data.Composition from the composition package.
(.) takes two functions that take one value and return a value:
(.) :: (b -> c) -> (a -> b) -> a -> c
Since (.) takes two arguments, I feel like (.).(.) should be invalid, but it's perfectly fine:
(.).(.) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c
What is going on here? I realize this question is badly worded...all functions really just take one argument thanks to currying. Maybe a better way to say it is that the types don't match up.
Let's first play typechecker for the mechanical proof. I'll describe an intuitive way of thinking about it afterward.
I want to apply (.) to (.) and then I'll apply (.) to the result. The first application helps us to define some equivalences of variables.
((.) :: (b -> c) -> (a -> b) -> a -> c)
((.) :: (b' -> c') -> (a' -> b') -> a' -> c')
((.) :: (b'' -> c'') -> (a'' -> b'') -> a'' -> c'')
let b = (b' -> c')
c = (a' -> b') -> a' -> c'
((.) (.) :: (a -> b) -> a -> c)
((.) :: (b'' -> c'') -> (a'' -> b'') -> a'' -> c'')
Then we begin the second, but get stuck quickly...
let a = (b'' -> c'')
This is key: we want to let b = (a'' -> b'') -> a'' -> c'', but we already defined b, so instead we must try to unify --- to match up our two definitions as best we can. Fortunately, they do match
UNIFY b = (b' -> c') =:= (a'' -> b'') -> a'' -> c''
which implies
b' = a'' -> b''
c' = a'' -> c''
and with those definitions/unifications we can continue the application
((.) (.) (.) :: (b'' -> c'') -> (a' -> b') -> (a' -> c'))
then expand
((.) (.) (.) :: (b'' -> c'') -> (a' -> a'' -> b'') -> (a' -> a'' -> c''))
and clean it up
substitute b'' -> b
c'' -> c
a' -> a
a'' -> a1
(.).(.) :: (b -> c) -> (a -> a1 -> b) -> (a -> a1 -> c)
which, to be honest, is a bit of a counterintuitive result.
Here's the intuition. First take a look at fmap
fmap :: (a -> b) -> (f a -> f b)
it "lifts" a function up into a Functor. We can apply it repeatedly
fmap.fmap.fmap :: (Functor f, Functor g, Functor h)
=> (a -> b) -> (f (g (h a)) -> f (g (h b)))
allowing us to lift a function into deeper and deeper layers of Functors.
It turns out that the data type (r ->) is a Functor.
instance Functor ((->) r) where
fmap = (.)
which should look pretty familiar. This means that fmap.fmap translates to (.).(.). Thus, (.).(.) is just letting us transform the parametric type of deeper and deeper layers of the (r ->) Functor. The (r ->) Functor is actually the Reader Monad, so layered Readers is like having multiple independent kinds of global, immutable state.
Or like having multiple input arguments which aren't being affected by the fmaping. Sort of like composing a new continuation function on "just the result" of a (>1) arity function.
It's finally worth noting that if you think this stuff is interesting, it forms the core intuition behind deriving the Lenses in Control.Lens.
Let’s ignore types for a moment and just use lambda calculus.
Desugar infix notation:
(.) (.) (.)
Eta-expand:
(\ a b -> (.) a b) (\ c d -> (.) c d) (\ e f -> (.) e f)
Inline the definition of (.):
(\ a b x -> a (b x)) (\ c d y -> c (d y)) (\ e f z -> e (f z))
Substitute a:
(\ b x -> (\ c d y -> c (d y)) (b x)) (\ e f z -> e (f z))
Substitute b:
(\ x -> (\ c d y -> c (d y)) ((\ e f z -> e (f z)) x))
Substitute e:
(\ x -> (\ c d y -> c (d y)) (\ f z -> x (f z)))
Substitute c:
(\ x -> (\ d y -> (\ f z -> x (f z)) (d y)))
Substitute f:
(\ x -> (\ d y -> (\ z -> x (d y z))))
Resugar lambda notation:
\ x d y z -> x (d y z)
And if you ask GHCi, you’ll find that this has the expected type. Why? Because the function arrow is right-associative to support currying: the type (b -> c) -> (a -> b) -> a -> c really means (b -> c) -> ((a -> b) -> (a -> c)). At the same time, the type variable b can stand for any type, including a function type. See the connection?
Here is a simpler example of the same phenomenon:
id :: a -> a
id x = x
The type of id says that id should take one argument. And indeed, we can call it with one argument:
> id "hello"
"hello"
But it turns out what we can also call it with two arguments:
> id not True
False
Or even:
> id id "hello"
"hello"
What is going on? The key to understanding id not True is to first look at id not. Clearly, that's allowed, because it applies id to one argument. The type of not is Bool -> Bool, so we know that the a from id's type should be Bool -> Bool, so we know that this occurrence of id has type:
id :: (Bool -> Bool) -> (Bool -> Bool)
Or, with less parentheses:
id :: (Bool -> Bool) -> Bool -> Bool
So this occurrence of id actually takes two arguments.
The same reasoning also works for id id "hello" and (.) . (.).
This is one of those neat cases where I think it's simpler to grasp the more general case first, and then think about the specific case. So let's think about functors. We know that functors provide a way to map functions over a structure --
class Functor f where
fmap :: (a -> b) -> f a -> f b
But what if we have two layers of the functor? For example, a list of lists? In that case we can use two layers of fmap
>>> let xs = [[1,2,3], [4,5,6]]
>>> fmap (fmap (+10)) xs
[[11,12,13],[14,15,16]]
But the pattern f (g x) is exactly the same as (f . g) x so we could write
>>> (fmap . fmap) (+10) xs
[[11,12,13],[14,15,16]]
What is the type of fmap . fmap?
>>> :t fmap.fmap
:: (Functor g, Functor f) => (a -> b) -> f (g a) -> f (g b)
We see that it maps over two layers of functor, as we wanted. But now remember that (->) r is a functor (the type of functions from r, which you might prefer to read as (r ->)) and its functor instance is
instance Functor ((->) r) where
fmap f g = f . g
For a function, fmap is just function composition! When we compose two fmaps we map over two levels of the function functor. We initially have something of type (->) s ((->) r a), which is equivalent to s -> r -> a, and we end up with something of type s -> r -> b, so the type of (.).(.) must be
(.).(.) :: (a -> b) -> (s -> r -> a) -> (s -> r -> b)
which takes its first function, and uses it to transform the output of the second (two-argument) function. So for example, the function ((.).(.)) show (+) is a function of two arguments, that first adds its arguments together and then transforms the result to a String using show:
>>> ((.).(.)) show (+) 11 22
"33"
There is then a natural generalization to thinking about longer chains of fmap, for example
fmap.fmap.fmap ::
(Functor f, Functor g, Functor h) => (a -> b) -> f (g (h a)) -> f (g (h b))
which maps over three layers of functor, which is equivalent to composing with a function of three arguments:
(.).(.).(.) :: (a -> b) -> (r -> s -> t -> a) -> (r -> s -> t -> b)
for example
>>> import Data.Map
>>> ((.).(.).(.)) show insert 1 True empty
"fromList [(1,True)]"
which inserts the value True into an empty map with key 1, and then converts the output to a string with show.
These functions can be generally useful, so you sometimes see them defined as
(.:) :: (a -> b) -> (r -> s -> a) -> (r -> s -> b)
(.:) = (.).(.)
so that you can write
>>> let f = show .: (+)
>>> f 10 20
"30"
Of course, a simpler, pointful definition of (.:) can be given
(.:) :: (a -> b) -> (r -> s -> a) -> (r -> s -> b)
(f .: g) x y = f (g x y)
which may help to demystify (.).(.) somewhat.
You're right, (.) only takes two arguments. You just seem to be confused with the syntax of haskell. In the expression (.).(.), it's in fact the dot in the middle that takes the other two dots as argument, just like in the expression 100 + 200, which can be written as (+) 100 200.
(.).(.) === (number the dots)
(1.)2.(3.) === (rewrite using just syntax rules)
(2.)(1.)(3.) === (unnumber and put spaces)
(.) (.) (.) ===
And it should be even more clear from (.) (.) (.) that the first (.) is taking the second (.) and third (.) as it's arguments.
Yes this is due to currying. (.) as all functions in Haskell only takes one argument. What you are composing is the first partial call to each respective composed (.) which takes its first argument (the first function of the composition).
(Read my answer on function composition, $ operator and point-free style first.)
Imagine you have a simple function: it adds up 2 numbers and then negates the result. We'll call it foo:
foo a b = negate (a + b)
Now let's make it point-free step by step and see what we end up with:
foo a b = negate $ a + b
foo a b = negate $ (+) a b
foo a b = negate $ (+) a $ b
foo a b = negate . (+) a $ b
foo a = negate . (+) a -- f x = g x is equivalent to f = g
foo a = (.) negate ((+) a) -- any infix operator is just a function
foo a = (negate.) ((+) a) -- (2+) is the same as ((+) 2)
foo a = (negate.) $ (+) a
foo a = (negate.) . (+) $ a
foo = (negate.) . (+)
foo = ((.) negate) . (+)
foo = (.) ((.) negate) (+) -- move dot in the middle in prefix position
foo = ((.) ((.) negate)) (+) -- add extra parentheses
Now let's analyze expression (.) ((.) negate) more closely. It's a partial application of (.) function, whose first argument is ((.) negate). Can we transform it even further? Yes we can:
(.) ((.) negate)
(.) . (.) $ negate -- because f (f x) is the same as (f . f) x
(.)(.)(.) $ negate
((.)(.)(.)) negate
(.).(.) is equivalent to (.)(.)(.), because in the 1st expression, the dot in the middle can be moved in prefix position and surrounded with parentheses, which gives rise to the 2nd expression.
Now we can rewrite our foo function:
foo = ((.).(.)) negate (+)
foo = ((.)(.)(.)) negate (+) -- same as previous one
foo = negate .: (+)
where (.:) = (.).(.)
Now you know that (.).(.) is equivalent to (\f g x y -> f (g x y)):
(\f g x y -> f (g x y)) negate (+) 2 3 -- returns -5
((.).(.)) negate (+) 2 3 -- returns -5