Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain where Applicative instances arise in this code?

isAlphaNum :: Char -> Bool
isAlphaNum = (||) <$> isAlpha <*> isNum 

I can see that it works, but I don't understand where the instances of Applicative (or Functor) come from.

like image 387
Peter Hall Avatar asked Jan 26 '12 02:01

Peter Hall


2 Answers

This is the Applicative instance for ((->) r), functions from a common type. It combines functions with the same first argument type into a single function by duplicating a single argument to use for all of them. (<$>) is function composition, pure is const, and here's what (<*>) translates to:

s :: (r -> a -> b) -> (r -> a) -> r -> b
s f g x = f x (g x)

This function is perhaps better known as the S combinator.

The ((->) r) functor is also the Reader monad, where the shared argument is the "environment" value, e.g.:

newtype Reader r a = Reader (r -> a)

I wouldn't say it's common to do this for the sake of making functions point-free, but in some cases it can actually improve clarity once you're used to the idiom. The example you gave, for instance, I can read very easily as meaning "is a character a letter or number".

like image 145
C. A. McCann Avatar answered Sep 28 '22 10:09

C. A. McCann


You get instances of what are called static arrows (see "Applicative Programming with Effects" by Conor McBride et al.) for free from the Control.Applicative package. So, any source type, in your case Char, gives rise to an Applicative instance where any other type a is mapped to the type Char -> a.

When you combine any of these, say apply a function f :: Char -> a -> b to a value x :: Char -> a, the semantic is that you create a new function Char -> b, which will feed its argument into both f and x like so,

f <*> x = \c -> (f c) (x c)

Hence, as you point out, this makes your example equivalent to

isAlphaNum c = (isAlpha c) || (isNum c)

In my opinion, such effort is not always necessary, and it would look nicer if Haskell had better syntactic support for applicatives (maybe something like 2-level languages).

like image 35
gatoatigrado Avatar answered Sep 28 '22 10:09

gatoatigrado