File: Applicative.hs

package info (click to toggle)
bali-phy 4.0~beta16%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 15,192 kB
  • sloc: cpp: 119,288; xml: 13,482; haskell: 9,722; python: 2,930; yacc: 1,329; perl: 1,169; lex: 904; sh: 343; makefile: 26
file content (47 lines) | stat: -rw-r--r-- 1,011 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{-# LANGUAGE NoImplicitPrelude #-}
module Control.Applicative where

import Data.Functor
import Data.Function
import Data.Maybe

infixl 4 <*>, <*, *>

class Functor f => Applicative f where
    pure :: a -> f a
    (<*>) :: f (a -> b) -> f a -> f b 
    liftA2 :: (a -> b -> c) -> f a -> f b -> f c 
    (*>) :: f a -> f b -> f b
    (<*) :: f a -> f b -> f a

    (<*>) = liftA2 id
    liftA2 f x y = f <$> x <*> y
    as *> bs = (\x y -> y) <$> as <*> bs
    as <* bs = (\x y -> x) <$> as <*> bs


infixl 3 <|>

class Applicative f => Alternative f where
    empty :: f a
    (<|>) :: f a -> f a -> f a
    some :: f a -> f [a]
    many :: f a -> f [a]

    many v = some v <|> pure []
--  Not working! some v = (:) <$> v <*> many v

-- These are defined by Parse.hs
-- <|>
-- some
-- many

instance Applicative [] where
    pure x = [x]
    fs <*> xs = [f x | f <- fs, x <- xs]

instance Applicative Maybe where
    pure x = Just x

    (Just f) <*> (Just x) = Just (f x)
    _        <*> _        = Nothing