Skip to content

Commit c818a1d

Browse files
committed
Added haskell implementation with monads
1 parent 785b136 commit c818a1d

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

Haskell/insane/DoubleLinked.hs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
module DoubleLinked where
2+
3+
import Control.Monad
4+
import Prelude hiding (fromList)
5+
6+
import SingleLinked as L hiding (fromList)
7+
8+
data DList a = DList {
9+
getDirect :: List a,
10+
getInverse :: List a
11+
}
12+
13+
instance Functor DList where
14+
fmap f (DList dir inv) = DList (appF dir) (appF inv)
15+
where appF = fmap f
16+
17+
empty :: DList a
18+
empty = DList Empty Empty
19+
20+
push :: a -> DList a -> DList a
21+
push el list = list {
22+
getDirect = addToEnd el $ getDirect list,
23+
getInverse = el :+: getInverse list
24+
}
25+
26+
pop :: DList a -> (a, DList a)
27+
pop (DList Empty Empty) = error "pop on empty list"
28+
pop (DList Empty _ ) = error "wrong structured list"
29+
pop (DList _ Empty) = error "wrong structured list"
30+
pop (DList dir (el:+:rest)) = (el, DList (L.init dir) rest)
31+
32+
fromList :: [a] -> DList a
33+
fromList = foldl (flip push) empty
34+
35+
node :: a -> DList a
36+
node = (`push` empty)
37+
38+
main = do
39+
let list3 = Human <$> fromList ["first", "second", "third"]
40+
printPop list = let (el, list') = pop list
41+
in print el >> return list'
42+
nPrintPop n = foldr (>=>) return
43+
$ replicate n printPop
44+
pushHuman name = return . push (Human name)
45+
foldr (>=>) return [
46+
nPrintPop 3,
47+
pushHuman "uno",
48+
pushHuman "due",
49+
printPop,
50+
pushHuman "tre",
51+
nPrintPop 2
52+
] list3
53+
return ()

Haskell/insane/SingleLinked.hs

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
module SingleLinked
2+
( List(..)
3+
, Human(..)
4+
, addToEnd
5+
, init
6+
, fromList
7+
) where
8+
9+
import Prelude hiding (init, fromList)
10+
11+
data List a = a :+: List a
12+
| Empty
13+
deriving (Show)
14+
infixr :+:
15+
16+
instance Functor List where
17+
fmap f Empty = Empty
18+
fmap f (x :+: xs) = f x :+: fmap f xs
19+
20+
data Human = Human {
21+
getName :: String
22+
} deriving (Show)
23+
24+
addToEnd :: a -> List a -> List a
25+
addToEnd el Empty = el :+: Empty
26+
addToEnd el (x:+:xs) = x :+: addToEnd el xs
27+
28+
init :: List a -> List a
29+
init Empty = error "init on empty list"
30+
init (x :+: Empty) = Empty
31+
init (x :+: xs) = x :+: init xs
32+
33+
fromList :: [a] -> List a
34+
fromList = foldr (:+:) Empty
35+
36+
main = do
37+
let (n1 :+: n2 :+: n3 :+: _) = fmap Human . fromList
38+
$ ["first", "second", "third"]
39+
print n1
40+
print n2
41+
print n3

0 commit comments

Comments
 (0)