Skip to content

Commit 0bf92d2

Browse files
authored
Merge pull request #1 from DzyubSpirit/master
Haskell implementation
2 parents f73bd1a + 493ddfb commit 0bf92d2

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

Haskell/maybe.hs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import Prelude hiding (Maybe(..), Functor, fmap, (<$>))
2+
3+
data Maybe a = Just a | Nothing
4+
deriving (Show)
5+
6+
class Functor f where
7+
fmap :: (a -> b) -> f a -> f b
8+
9+
(<$>) :: Functor f => (a -> b) -> f a -> f b
10+
(<$>) = fmap
11+
infixl 4 <$>
12+
13+
instance Functor Maybe where
14+
fmap f (Just x) = Just $ f x
15+
fmap _ Nothing = Nothing
16+
17+
main = do
18+
print $ (* 2) <$> Just 5
19+
print $ (* 2) <$> Nothing

Haskell/maybe2.hs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
main = do
2+
print $ (* 2) . (+ 5) . (^ 2) <$> Just 5
3+
print $ (* 2) . (+ 5) . (^ 2) <$> Nothing

Haskell/maybe3.hs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import Prelude hiding (Applicative(..))
2+
3+
class Functor f => Applicative f where
4+
pure :: a -> f a
5+
(<*>) :: f (a -> b) -> f a -> f b
6+
(*>) :: f a -> f b -> f b
7+
(<*) :: f a -> f b -> f a
8+
9+
a *> b = fmap const b <*> a
10+
(<*) = flip (*>)
11+
{-# MINIMAL pure, (<*>) #-}
12+
13+
instance Applicative Maybe where
14+
pure = Just
15+
(Just f) <*> v = fmap f v
16+
Nothing <*> _ = Nothing
17+
18+
main = do
19+
let a = Just 5
20+
b = Just $ (* 2) . (+ 5) . (^ 2)
21+
c = b <*> a
22+
print c
23+
24+

0 commit comments

Comments
 (0)