I'm new to Haskell. In the Monad docs, there is an example use for the void function:
>>> void (Left 8675309)
Left 8675309
>>> void (Right 8675309)
Right ()
I'm having a tough time figuring out why this is the case.
I see that void is defined as: void x = () <$ x
and (<$) = fmap . const
but I cannot figure out why there is a difference between Left and Right.
Any hints?
The absurd function in Data.Void has the following signature, where Void is the logically uninhabited type exported by that package: -- | Since 'Void' values logically don't exist, this witnesses the logical -- reasoning tool of \"ex falso quodlibet\".
No. However, you can have functions that return a trivial value.
Haskell - Functions. Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output.
Haskell has a built-in function called error whose type is String->a. This is a somewhat odd function: From its type it looks as if it is returning a value of a polymorphic type about which it knows nothing, since it never receives a value of that type as an argument!
In this section, we look at several aspects of functions in Haskell. First, consider this definition of a function which adds its two arguments: add :: Integer -> Integer -> Integer. add x y = x + y. This is an example of a curried function.
But this is not so in Haskell. As a simple example, consider const1, the constant 1 function, defined by: const1 x = 1 The value of const1 botin Haskell is 1. Operationally speaking, since const1does not "need" the value of its argument, it never attempts to evaluate it, and thus never gets caught in a nonterminating computation.
Because fmap
maps the value defined in the Right
, not in the Left
. Indeed, Either
is defined as:
data Either a b = Left a | Right b
and the Functor
of Either a
is thus implemented as:
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right x) = Right (f x)
This makes sense, since the Functor
expects a type of kind * -> *
, and thus the fmap :: Functor f => (b -> c) -> f b -> f c
makes a mapping for Either
with fmap :: (b -> c) -> Either a b -> Either a c
.
Since void
is defined as void = fmap (const ())
, this thus means that if we make an analysis per case, we see:
fmap (const ()) (Left x) = Left x
fmap (const ()) (Right x) = Right (const () x) = Right ()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With