Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Haskell/maybe.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Prelude hiding (Maybe(..), Functor, fmap, (<$>))

data Maybe a = Just a | Nothing
deriving (Show)

class Functor f where
fmap :: (a -> b) -> f a -> f b

(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap
infixl 4 <$>

instance Functor Maybe where
fmap f (Just x) = Just $ f x
fmap _ Nothing = Nothing

main = do
print $ (* 2) <$> Just 5
print $ (* 2) <$> Nothing
3 changes: 3 additions & 0 deletions Haskell/maybe2.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
main = do
print $ (* 2) . (+ 5) . (^ 2) <$> Just 5
print $ (* 2) . (+ 5) . (^ 2) <$> Nothing
24 changes: 24 additions & 0 deletions Haskell/maybe3.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Prelude hiding (Applicative(..))

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

a *> b = fmap const b <*> a
(<*) = flip (*>)
{-# MINIMAL pure, (<*>) #-}

instance Applicative Maybe where
pure = Just
(Just f) <*> v = fmap f v
Nothing <*> _ = Nothing

main = do
let a = Just 5
b = Just $ (* 2) . (+ 5) . (^ 2)
c = b <*> a
print c