Why does <$> act only on the second member of a pair? - haskell

Take a quick peek at the following interactive session in GHCi:
Prelude> import Control.Applicative
Prelude Control.Applicative> (+1) <$> [1,2]
[2,3]
Prelude Control.Applicative> (+1) <$> (1,2)
(1,3)
I guess there is a good reason for the behavior of <$> regarding pairs, but I wasn't able to find one so far, so:
Why is <$> (or fmap) defined to act only on the second member of a pair and not on both values?

<$> (aka fmap) is a member of the Functor class like so:
class Functor f where
fmap :: (a -> b) -> f a -> f b
So whatever f is must be a parameterised type with one type argument. Lists are one such type, when written in their prefix form [] ([] a is the same as [a]). So the instance for lists is:
instance Functor [] where
-- fmap :: (a -> b) -> [] a -> [] b
fmap = map
Pairs can also be written in prefix form: (,) a b is the same as (a, b). So let's consider what we do if we want a Functor instance involving pairs. We can't declare an instance Functor (,) because the pair constructor (,) takes two types -- and they can be different types! What we can do is declare an instance for (,) a -- that's a type that only needs one more type:
instance Functor ( (,) a ) where
-- fmap :: (b -> c) -> (,) a b -> (,) a c
fmap f (x, y) = (x, f y)
Hopefully you can see that the definition of fmap is the only sensible one we can give. The answer as to why the functor instance operates on the second item in a pair is that the type for the second item comes last in the list! We can't easily declare a functor instance that operates on the first item in a pair. Incidentally, this generalises to larger tuples, e.g. the quadruple (,,,) a b c d (aka (a, b, c, d)) can also have a Functor instance on the last item:
instance Functor ( (,,,) a b c) where
-- fmap :: (d -> e) -> (,,,) a b c d -> (,,,) a b c e
fmap f (p, q, r, s) = (p, q, r, f s)
Hope that helps explain it all!

Consider the definition of the Functor typeclass:
class Functor f where
fmap :: (a -> b) -> f a -> f b
Obviously, f has kind * -> *. So you can only declare instances for a datatype, which has kind * -> *. What you can do, is doing some stuff like this:
instance Functor (,) where
fmap :: (a -> b) -> (,) a -> (,) b
This would work on partitial applicated tuples and is really unhandy. So one defined the instance like this:
instance Functor ((,) a) where
fmap :: (b -> c) -> (,) a b -> (,) a c
fmap f (x,y) = (x,f y)
In a nutshell: It is not possible in plain Haskell 98 (although I believe tht there's a syntax extension for this) to define an instance as
What you can do, is defining your own tuple:
data T a = T a a
instance Functor T where
fmap f (T a b) = T (f a) (f b)
Then you can do whatever you like. You see, because the kind is * -> * instead of * -> * -> *, anything's okay.

I guess, a tuple doesn't need to be homogeneous, I mean both types can be different. If you want a homogeneous tuple you can use a list and then fmap will work.
How would you expect (+1) ("Hello", 2) to work ?
Prelude> import Control.Applicative
Prelude Control.Applicative> (+1) <$> ("hello",2)
("hello",3)
That's just work, but there is not special behavior when both type are same.
By the way I don't know why the second value is not used rather than the first one, but anyway you can only use one value.

Related

Flip functor instance Haskell

I need to write the Functor instances for the Flip datatype:
data K a b = K a
newtype Flip f a b = Flip (f b a) deriving (Eq, Show)
instance Functor (Flip K a) where
fmap=undefined
The solution I was given in class is:
instance Functor (Flip K a) where
fmap f (Flip (K b)) = Flip (K (f b))
I really don't understand what's going on here and I'm beginning to doubt my whole understanding of data types and functors. What I do understand is this (please correct me if any of this is wrong):
K is a data type that turns 2 parameters into a structure K a ( that only keeps the first parameter)
Flip is a datatype that turns 3 arguments into a structure with one
Because in fmap :: (a-> b) -> f a -> f b, f a has kind *, to write the Functor instance of Flip, we write it on the last type in Flip. Aka f and a are "constants" in a way, and we write the functor for the type b. I would write something like:
instance Functor (Flip f a) where
fmap f (Flip x y z) = fmap Flip x y (f z)
I know that that is completely wrong but I'm not sure why.
Also, why would we bring K into the Functor instance of Flip? Can someone explain thoroughly the process of coming up with this solution and why it is correct?
K is a data type that turns 2 parameters into a structure K a ( that only keeps the first parameter)
This isn't quite right. K a b is a data type formed using two parameters, but it's not really right to say that it "turns them into" anything. Instead, it's simply just stating to the world that there now exists a new type: K a b. "So what?" you might ask. Well, the second half of the data type defines how to make new values of this type. That part says, "You can make a new value of type K a b with this function I'll call K which has type a -> K a b." It's really important to recognize that there is a distinction between the type K and the constructor K.
So, it's not that K "only keeps the first parameter"—it's that the constructor K (which is a function) happens to not take any arguments of type b.
Flip is a datatype that turns 3 arguments into a structure with one
Just as above, this is not quite right. The Flip declaration states that there can be values of type Flip f a b, and the only way to make them is by using the constructor Flip that has type f b a -> Flip f a b.
In case you're wondering how I'm coming up with the type signatures for the constructors K and Flip, it's not actually mysterious, and you can double check by typing :t K or :t Flip into GHCi. These types are assigned based entirely on the right hand side of the data type declaration. Also, note that the type name and constructor don't have to be the same. For instance, consider this data type:
data Foo a = Bar Int a | Foo String | Baz a a
This declares a type Foo a with three constructors:
Bar :: Int -> a -> Foo a
Foo :: String -> Foo a
Baz :: a -> a -> Foo a
Basically, each of the types after the constructor name are the arguments, in order, to the constructor.
Because in fmap :: (a-> b) -> f a -> f b, f a has kind *, to write the Functor instance of Flip, we write it on the last type in Flip. Aka f and a are "constants" in a way, and we write the functor for the type b.
This is basically right! You could also say that f has kind * -> *. Since Flip has kind (* -> *) -> * -> * -> *, you need to provide it two type arguments (the first of kind * -> * and the second of kind *) to get it to the right kind. Those first two arguments become fixed ("constants" in a way) in the instance.
I would write something like: ... I know that that is completely wrong but I'm not sure why.
The reason your instance is completely wrong is that you've mixed up the type with the constructor. It doesn't make sense to put (Flip x y z) in the pattern position where you did because the constructor Flip only takes one argument—remember, it's type is Flip :: f b a -> Flip f a b! So you'd want to write something like:
instance Functor (Flip f a) where
fmap f (Flip fxa) = ...
Now, what do you fill in for the ...? You have a value fxa :: f x a, and you have a function f :: x -> y, and you need to produce a value of type f y a. Honestly, I don't know how to do that. After all, what is a value of typ f x a? We don't know what f is?!
Also, why would we bring K into the Functor instance of Flip? Can someone explain thoroughly the process of coming up with this solution and why it is correct?
We saw just above that we can't write the Functor instance for an arbitrary f, but what we can do is write it for a particular f. It turns out that K is just such a particular f that works. Let's try to make it work:
instance Functor (Flip K a) where
fmap f (Flip kxa) = ...
When f was arbitrary, we got stuck here, but now we know that kxa :: K x a. Remember that the only way to make a value of type K x a is using the constructor K. Therefore, this value kxa must have been made using that constructor, so we can break it apart as in: kxa ⩳ K x' where x' :: x. Let's go ahead and put that into our pattern:
fmap f (Flip (K x')) = ...
Now we can make progress! We need to produce a value of type Flip K a y. Hmm. The only way to produce a value of type Flip is using the Flip constructor, so let's start with that:
fmap f (Flip (K x')) = Flip ...
The Flip constructor at type Flip K a y takes a value of type K y a. The only way to produce one of those is with the K constructor, so let's add that:
fmap f (Flip (K x')) = Flip (K ...)
The K constructor at type K y a takes a value of type y, so we need to provide a value of type y here. We have a value x' :: x and a function f :: x -> y. Plugging the first into the second gives us the value we need:
fmap f (Flip (K x')) = Flip (K (f x'))
Just rename x' to b, and you have exactly the code your teacher provided.
DDub wrote in their answer:
You have a value fxa :: f x a, and you have a function f :: x -> y, and you need to produce a value of type f y a. Honestly, I don't know how to do that. After all, what is a value of type f x a? We don't know what f is?!
And I agree, but I woulld like to add a bit. Your teacher's idea as to how to deal with this is pretty cool (things like this K come in quite handy when you are trying to write down some counterexample, like here), and yet, I reckon we can make this code way broader. I use Data.Bifunctor.
So, what are Bifunctors? They are just what their name says: a * -> * -> * type (which we call bifunctors as well sometimes, yet they are not the same thing) which allows mapping over its both arguments (snippet from the source):
class Bifunctor p where
-- | Map over both arguments at the same time.
--
-- #'bimap' f g ≡ 'first' f '.' 'second' g#
bimap :: (a -> b) -> (c -> d) -> p a c -> p b d
bimap f g = first f . second g
{-# INLINE bimap #-}
-- | Map covariantly over the first argument.
--
-- #'first' f ≡ 'bimap' f 'id'#
first :: (a -> b) -> p a c -> p b c
first f = bimap f id
{-# INLINE first #-}
-- | Map covariantly over the second argument.
--
-- #'second' ≡ 'bimap' 'id'#
second :: (b -> c) -> p a b -> p a c
second = bimap id
{-# INLINE second #-}
So, here is how I would go about that:
instance Bifunctor f => Functor (Flip f a) where
fmap x2y (Flip fxa) = Flip (first x2y fxa)
Speaking of your teacher's code, it's a very nice idea, yet a more narrow one as K is a Bifunctor:
instance Bifunctor K where
bimap f _g (K a) = K (f a)
A lawful one:
bimap id id (K a) = K (id a) = id (K a)
As it says in the link above, having bimap only written down, that's the only law we need to worry about.
We just need to use sane and helpful naming, and suddenly it all becomes simple and clear (as opposed to torturous and contorted):
data K b a = MkK b -- the type (K b a) "is" just (b)
newtype Flip f a b = MkFlip (f b a) -- the type (Flip f a b) "is" (f b a)
deriving (Eq, Show)
instance Functor (Flip K a) where
-- fmap :: (b -> c) -> Flip K a b -> Flip K a c
fmap g (MkFlip (MkK b)) = MkFlip (MkK (g b))
-- MkK b :: K b a
-- MkFlip (_ :: K b a) :: Flip K a b
There's not even one question arising in our minds now looking at this, not one doubt we aren't able to immediately resolve.
Using same names for types and for data constructors while teaching, as well as using f both for "f"unction and "f"unctor, is pure abuse of the students.
Only when you've become fed up with all the Mks and don't feel they are helpful to you in any way, you can safely and easily throw them away, as experts usually do.

How are monoid and applicative connected?

I am reading in the haskellbook about applicative and trying to understand it.
In the book, the author mentioned:
So, with Applicative, we have a Monoid for our structure and function
application for our values!
How is monoid connected to applicative?
Remark: I don't own the book (yet), and IIRC, at least one of the authors is active on SO and should be able to answer this question. That being said, the idea behind a monoid (or rather a semigroup) is that you have a way to create another object from two objects in that monoid1:
mappend :: Monoid m => m -> m -> m
So how is Applicative a monoid? Well, it's a monoid in terms of its structure, as your quote says. That is, we start with an f something, continue with f anotherthing, and we get, you've guessed it a f resulthing:
amappend :: f (a -> b) -> f a -> f b
Before we continue, for a short, a very short time, let's forget that f has kind * -> *. What do we end up with?
amappend :: f -> f -> f
That's the "monodial structure" part. And that's the difference between Applicative and Functor in Haskell, since with Functor we don't have that property:
fmap :: (a -> b) -> f a -> f b
-- ^
-- no f here
That's also the reason we get into trouble if we try to use (+) or other functions with fmap only: after a single fmap we're stuck, unless we can somehow apply our new function in that new structure. Which brings us to the second part of your question:
So, with Applicative, we have [...] function application for our values!
Function application is ($). And if we have a look at <*>, we can immediately see that they are similar:
($) :: (a -> b) -> a -> b
(<*>) :: f (a -> b) -> f a -> f b
If we forget the f in (<*>), we just end up with ($). So (<*>) is just function application in the context of our structure:
increase :: Int -> Int
increase x = x + 1
five :: Int
five = 5
increaseA :: Applicative f => f (Int -> Int)
increaseA = pure increase
fiveA :: Applicative f => f Int
fiveA = pure 5
normalIncrease = increase $ five
applicativeIncrease = increaseA <*> fiveA
And that's, I guessed, what the author meant with "function application". We suddenly can take those functions that are hidden away in our structure and apply them on other values in our structure. And due to the monodial nature, we stay in that structure.
That being said, I personally would never call that monodial, since <*> does not operate on two arguments of the same type, and an applicative is missing the empty element.
1 For a real semigroup/monoid that operation should be associative, but that's not important here
Although this question got a great answer long ago, I would like to add a bit.
Take a look at the following class:
class Functor f => Monoidal f where
unit :: f ()
(**) :: f a -> f b -> f (a, b)
Before explaining why we need some Monoidal class for a question about Applicatives, let us first take a look at its laws, abiding by which gives us a monoid:
f a (x) is isomorphic to f ((), a) (unit ** x), which gives us the left identity. (** unit) :: f a -> f ((), a), fmap snd :: f ((), a) -> f a.
f a (x) is also isomorphic f (a, ()) (x ** unit), which gives us the right identity. (unit **) :: f a -> f (a, ()), fmap fst :: f (a, ()) -> f a.
f ((a, b), c) ((x ** y) ** z) is isomorphic to f (a, (b, c)) (x ** (y ** z)), which gives us the associativity. fmap assoc :: f ((a, b), c) -> f (a, (b, c)), fmap assoc' :: f (a, (b, c)) -> f ((a, b), c).
As you might have guessed, one can write down Applicative's methods with Monoidal's and the other way around:
unit = pure ()
f ** g = (,) <$> f <*> g = liftA2 (,) f g
pure x = const x <$> unit
f <*> g = uncurry id <$> (f ** g)
liftA2 f x y = uncurry f <$> (x ** y)
Moreover, one can prove that Monoidal and Applicative laws are telling us the same thing. I asked a question about this a while ago.

Why does the 2-tuple Functor instance only apply the function to the second element?

import Control.Applicative
main = print $ fmap (*2) (1,2)
produces (1,4). I would expect it it to produce (2,4) but instead the function is applied only to the second element of the tuple.
Update I've basically figured this out almost straight away. I'll post my own answer in a minute..
Let me answer this with a question: Which output do you expect for:
main = print $ fmap (*2) ("funny",2)
You can have something as you want (using data Pair a = Pair a a or so), but as (,) may have different types in their first and second argument, you are out of luck.
Pairs are, essentially, defined like this:
data (,) a b = (,) a b
The Functor class looks like this:
class Functor f where
fmap :: (a -> b) -> f a -> f b
Since the types of function arguments and results must have kind * (i.e. they represent values rather than type functions that can be applied further or more exotic things), we must have a :: *, b :: *, and, most importantly for our purposes, f :: * -> *. Since (,) has kind * -> * -> *, it must be applied to a type of kind * to obtain a type suitable to be a Functor. Thus
instance Functor ((,) x) where
-- fmap :: (a -> b) -> (x,a) -> (x,b)
So there's actually no way to write a Functor instance doing anything else.
One useful class that offers more ways to work with pairs is Bifunctor, from Data.Bifunctor.
class Bifunctor f where
bimap :: (a -> b) -> (c -> d) -> f a c -> f b d
bimap f g = first f . second g
first :: (a -> b) -> f a y -> f b y
first f = bimap f id
second :: (c -> d) -> f x c -> f x d
second g = bimap id g
This lets you write things like the following (from Data.Bifunctor.Join):
newtype Join p a =
Join { runJoin :: p a a }
instance Bifunctor p => Functor (Join p) where
fmap f = Join . bimap f f . runJoin
Join (,) is then essentially the same as Pair, where
data Pair a = Pair a a
Of course, you can also just use the Bifunctor instance to work with pairs directly.
The Functor instance is actually from the GHC.Base module which is imported by Control.Applicative.
Trying to write the instance I want, I can see that it won't work, given the definition of tuples; the instance requires just one type parameter, while the 2-tuple has two.
A valid Functor instance would at least have to be on tuples, (a,a) that have the same type for each element, but you cannot do anything sneaky, like define the instance on:
type T2 a = (a,a)
because instance types aren't permitted to be synonyms.
The above restricted 2-tuple synonym is logically the same as the type:
data T2 a = T2 a a
which can have a Functor instance:
instance Functor T2 where
fmap f (T2 x y) = T2 (f x) (f y)
As Gabriel remarked in the comments, this can be useful for branching structures or concurrency.

confused about function as instance of Functor in haskell

The type of fmap in Functor is:
fmap :: Functor f => (a -> b) -> f a -> f b
it looks like ,first apply function (a -> b) to the parameter of f a to create a result of type b, then apply f to it, and result is f b
using Maybe a for example:
fmap show (Just 1)
result is : Just "1"
same as saying:
Just (show 1)
but when (->) is used as a Functor (in Control.Monad.Instances)
import Control.Monad.Instances
(fmap show Just) 1
result is : "Just 1"
that is, Just is applied first, then show is applied. In another example ,result is same:
fmap (*3) (+100) 1
result is 303
why not *3 first, then +100?
The fmap instance for (->) r (i.e. functions) is literally just composition. From the source itself:
instance Functor ((->) r) where
fmap = (.)
So, in your example, we can just replace fmap with (.), and do some transformations
fmap (*3) (+100) 1 =>
(.) (*3) (+100) 1 =>
(*3) . (+100) $ 1 => -- put (.) infix
(*3) (1 + 100) => -- apply (+100)
(1 + 100) * 3 -- apply (*3)
That is, fmap for functions composes them right to left (exactly the same as (.), which is sensible because it is (.)).
To look at it another way (for (double) confirmation!), we can use the type signature:
-- general fmap
fmap :: Functor f => (a -> b) -> f a -> f b
-- specialised to the function functor (I've removed the last pair of brackets)
fmap :: (a -> b) -> (r -> a) -> r -> b
So first the value of type r (the third argument) needs to be transformed into a value of type a (by the r -> a function), so that the a -> b function can transform it into a value of type b (the result).
the type of fmap in Functor is:
fmap :: Functor f => (a -> b) -> f a -> f b
it looks like ,first apply function (a -> b) to the parameter of f a
to create a result of type b, then apply f to it, and result is f b
That is the type of fmap, but your interpretation of what that type means is wrong.
You seem to assume that f a has one parameter, and that that parameter has type a.
Consider xs :: [a]:
Perhaps xs = [].
Perhaps xs = [x1].
Perhaps xs = [x1, x2].
...
The type f a is a functor f with a single type parameter a. But values of type f a do not necessarily take the form F x, as you can see from the first and third cases above.
Now consider fmap f xs:
Perhaps fmap f xs = [].
Perhaps fmap f xs = [f x1].
Perhaps fmap f xs = [f x1, f x2].
...
We don't necessarily apply f at all (first case)! Or we might apply it more than once (third case).
What we do is replace the things of type a, with things of type b. But we leave the larger structure intact --- no new elements added, no elements removed, their order is left unchanged.
Now let's think about the functor (c ->). (Remember, a functor takes one type parameter only, so the input to (->) is fixed.)
Does a c -> a even contain an a? It might not contain any as at all, but it can somehow magic one out of thin air when we give it a c. But the result from fmap has type c -> b: we only have to provide a b out of that when we're presented with a c.
So we can say fmap f x = \y -> f (x y).
In this case, we're applying f on demand --- every time the function we return gets applied, f gets applied as well.
It needs to be defined that way to make the types work out. As you pointed out, the type of fmap is:
fmap :: Functor f => (a -> b) -> f a -> f b
Let's consider the case when the functor f is ((->) c)
(Note: we'd actually like to write this as (c ->), i.e. functions from c, but Haskell doesn't allow us to do this.)
Then f a is actually ((->) c a), which is equivalent to (c -> a), and similarly for f b, so we have:
fmap :: (a -> b) -> (c -> a) -> (c -> b)
i.e. we need to take two functions:
f :: a -> b
g :: c -> a
and construct a new function
h :: c -> b
But there's only one way to do that: you have to apply g first to get something of type a, and then apply f to get something of type b, which means that you have to define
instance Functor ((->) c) where
fmap f g = \x -> f (g x)
or, more succinctly,
instance Functor ((->) c) where
fmap = (.)
fmap for (->) is defined like fmap = (.).
So, (fmap f g) x is (f . g) x is f (g x). In your case (*3) ((+100) 1), which equals 3 * (100 + 1) which results in 303.
In order to form a function type, you need 2 kind parameters for (->), that is the single input argument type and the return type.
A Functor can only take 1 type parameter, so you have to nail down the input argument type(since it's the first one from left to right), which makes the return type of the function to be the type parameter of the Functor.
So for function (the Functor) a->b, you need to give fmap a function ff of type b->xxx other than a->xxx to work, and that means the function ff can only be applied after a->b is apply.

Manipulating the order of arguments to type constructors

I wrote something like this:
instance Functor (Either e) where
fmap _ (Left a) = Left a
fmap f (Right b) = Right (f b)
How do I do the same if I want fmap to change the value only if it's Left?
I mean, what syntax do I use to indicate that I use type Either _ b instead of Either a _?
I don't think there's a way to do that directly, unfortunately. With a function you can use flip to partially apply the second argument, but that doesn't work with type constructors like Either.
The simplest thing is probably wrapping it in a newtype:
newtype Mirror b a = Mirrored (Either a b)
instance Functor (Mirror e) where
fmap _ (Mirrored (Right a)) = Mirrored $ Right a
fmap f (Mirrored (Left b)) = Mirrored $ Left (f b)
Wrapping with newtype is also the standard way to create multiple instances for a single type, such as Sum and Product being instances of Monoid for numeric types. Otherwise, you can only have one instance per type.
Additionally, depending on what it is you want to do, another option is to ignore Functor and define your own type class like this:
class Bifunctor f where
bimap :: (a -> c) -> (b -> d) -> f a b -> f c d
instance Bifunctor Either where
bimap f _ (Left a) = Left $ f a
bimap _ g (Right b) = Right $ g b
instance Bifunctor (,) where
bimap f g (a, b) = (f a, g b)
Obviously, that class is twice as much fun as a regular Functor. Of course, you can't make a Monad instance out of that very easily.
You can't make the instance you are looking for directly.
In order for type inference and type classes to work, there is a certain positional bias to the ordering of arguments in the types. It has been shown that if we allowed arbitrary reordering of the arguments when instantiating type classes, that type inference becomes intractable.
You could use a Bifunctor class that can map over both arguments separately.
class Bifunctor f where
bimap :: (a -> b) -> (c -> d) -> f a c -> f b d
first :: (a -> b) -> f a c -> f b c
second :: (c -> d) -> f a c -> f a d
first f = bimap f id
second = bimap id
instance Bifunctor Either where
bimap f _ (Left a) = Left (f a)
bimap _ g (Right b) = Right (g b)
instance Bifunctor (,) where
bimap f g (a,b) = (f a, g b)
Or you could use a Flip combinator like:
newtype Flip f a b = Flip { unFlip :: f b a }
Generalized versions of both of these are available in category-extras on hackage. The latter even includes an instance for Functor (Flip Either a) because Either is a Bifunctor. (I should probably fix that to only require a PFunctor)
Ultimately, the order of arguments in a type constructor is important in determining what classes you can instantiate. You may need to use newtype wrappers (like Flip above) to put the arguments where they need to be to qualify to construct an instance of another typeclass. This is the price we pay for the inference of type class constraints.
You essentially need a 'flip' combinator on types. A newtype wrapper that inverts the order should work, as camccann says. Note that you can't use a 'type' synonym, as they may not be partially applied.

Resources