-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStaq.hs
38 lines (34 loc) · 1000 Bytes
/
Staq.hs
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
module Staq where
import List (intercalate)
-- queue (kinda) efficiently implemented as 2 stacks
type Staq a = ([a],[a])
newStaq :: [a] -> Staq a
newStaq xs = (xs,[])
deq :: Eq a => Staq a -> Maybe a
deq (e,d)
| d == []
, e == [] = Nothing
| d == []
, e /= [] = Just $ head $ reverse e
| otherwise = Just $ head d
rest :: Eq a => Staq a -> Maybe (Staq a)
rest (e,d)
| d == []
, e == [] = Nothing
| d == []
, e /= [] = Just $ ([], tail $ reverse e)
| otherwise = Just $ (e, tail d)
enq :: Staq a -> a -> Staq a
enq (e,d) i = (i:e,d)
flush :: Staq a -> [a]
flush ([],[]) = []
flush (e,[]) = flush ([], reverse e)
flush (e,(d:ds)) = d:flush (e,ds)
main :: IO ()
main = do
let q = ([6,5,4],[1,2,3]) :: Staq Int
print $ q
print $ flush q
let nth q n = iterate (>>= rest) (Just q) !! n
let showStaq q = (\d r -> intercalate ":" [show d, show r]) <$> (deq q) <*> (rest q)
mapM_ print $ (\n -> (nth q n) >>= showStaq) <$> [0,1,2,3,4,5]