[Haskell-beginners] Here's why functions should return functions

Ertugrul Söylemez es at ertes.de
Tue Jul 31 03:56:12 CEST 2012


"Carlos J. G. Duarte" <carlos.j.g.duarte at gmail.com> wrote:

> So, what is the usefulness of that "const" function anyway? (go easy
> on me, I'm just beginning on this)

There are many functions in Haskell, which you wouldn't define in most
other languages, including:

    const :: a -> b -> a
    flip  :: (a -> b -> c) -> (b -> a -> c)
    id    :: a -> a

They become useful when used as arguments to combinators.  Some
examples:

    maybe 8 (const 16)
    foldl' (flip (-)) 0
    id &&& length

In use:

    maybe 8 (const 16) (Just 3) = 16 = const 16 3
    maybe 8 (const 16) Nothing  = 8

    foldl' (flip (-)) 0 [1,2,3]
        = flip (-) (flip (-) (flip (-) 0 1) 2) 3
        = (-) 3 ((-) 2 ((-) 1 0))
        = 3 - (2 - (1 - 0))

    map (id &&& length) ["abc", "de", "f"]
        = [("abc", 3),
           ("de", 2),
           ("f", 1)]


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120731/c4de64e8/attachment.pgp>


More information about the Beginners mailing list