December 1, 2012
Arrows provide a generalization for monads, which was introduced by John Hughes. The arrows package provides classes that extend the Arrows class. It is now available in Fedora. Install it using:
$ sudo yum install ghc-arrows-devel
Consider the identity function defined using the arrows notation:
{-# LANGUAGE Arrows #-}
import Control.Arrow (returnA)
idA :: a -> a
idA = proc a -> returnA -< a
The idA function returns the given input as shown below:
*Main> idA 6
6
*Main> idA True
True
*Main> idA "Eureka!"
"Eureka!"
A mulTwo function that multiplies an integer by two can be written as:
{-# LANGUAGE Arrows #-}
import Control.Arrow (returnA)
mulTwo :: Int -> Int
mulTwo = proc a -> returnA -< (a * 2)
Testing mulTwo with ghci:
*Main> mulTwo 4
8
*Main> mulTwo 5
10
We can also use the do notation with arrows. For example:
{-# LANGUAGE Arrows #-}
import Control.Arrow (returnA)
mulFour :: Int -> Int
mulFour = proc a -> do b <- mulTwo -< a
mulTwo -< b
Loading mulFour in ghci:
*Main> mulFour 2
8
*Main> mulFour 3
12
Arrows also supports the use of conditional statements. An example when used with the if … then … else construct is as follows:
{-# LANGUAGE Arrows #-}
import Control.Arrow (returnA)
condMul :: Int -> Int
condMul = proc a ->
if a < 5
then returnA -< (a * 2)
else returnA -< (a * 3)
The condMul function multiplies the input integer by two if it is less than five, and with three when greater than five:
*Main> condMul 2
4
*Main> condMul 6
18