Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Fix where
  2. import Prelude hiding   ( repeat
  3.                         , map
  4.                         , foldr
  5.                         , foldl
  6.                         , iterate
  7.                         , zip
  8.                         , zipWith
  9.                         , cycle
  10.                         )
  11. import Data.Function
  12. import Nat
  13.  
  14. data BinTree a = Leaf a | Node ( BinTree a) ( BinTree a)
  15.  
  16. map :: (a -> b) -> [a] -> [b]
  17. map f = fix $ \m xs -> case xs of
  18.     []   -> []
  19.     y:ys -> f y : m ys
  20.  
  21. -- правая свертка через fix
  22. foldr :: (a -> b -> b) -> b -> [a] -> b
  23. foldr f = fix $ \fr ini xs -> case xs of
  24.     []      -> ini
  25.     y:ys    -> y `f` fr ini ys
  26.  
  27. -- левая свертка через fix
  28. foldl :: (b -> a -> b) -> b -> [a] -> b
  29. foldl f = fix $ \fl ini xs -> case xs of
  30.     []      -> ini
  31.     y:ys    -> f ini y `fl` ys
  32.  
  33. -- zip'ы через fix
  34. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
  35. zipWith f = fix $ \z x y -> if null x || null y
  36.     then []
  37.     else f (head x) (head y) : z (tail x) (tail y)
  38.  
  39. zip :: [a] -> [b] -> [(a, b)]
  40. zip = zipWith (,)
  41.  
  42. -- repeat через fix
  43. repeat :: a -> [a]
  44. repeat = fix . (:)
  45.  
  46. --iterate через fix
  47. iterate :: (a -> a) -> a -> [a]
  48. iterate f = fix $ \i x -> x : i (f x)
  49.  
  50. cycle :: [a] -> [a]
  51. cycle = fix . (++)
  52.  
  53. instance Num a => Num (BinTree a) where
  54.     (+) (Leaf _) x = x
  55.     (+) (Node l r) x = Node (l + x) r
  56.     (*) (Leaf a) (Leaf b) = Leaf (a*b)
  57.     (*) (Node l r) (Node l1 r1) = Node(l*l1) (r*r1)
  58.     (*) _ _ = error "oshibka"
  59.  
  60. sumTree :: (a -> a -> a) -> BinTree a -> BinTree b -> BinTree c
  61. sumTree f = fix $ \s x y -> case x of
  62.     (Leaf _)  -> s x
  63.     (Node l r)  -> s l+y r
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement