Guest User

Untitled

a guest
Apr 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. foo :: [a] -> Bool
  2. foo xs = length xs == 100
  3.  
  4. foo :: [a] -> Bool
  5. foo xs = length (take 101 xs) == 100
  6.  
  7. length :: FiniteList a -> Int
  8. foo :: FiniteList a -> Bool
  9.  
  10. -- assume n >= 0
  11. lengthIs 0 [] = True
  12. lengthIs 0 _ = False
  13. lengthIs n [] = False
  14. lengthIs n (x:xs) = lengthIs (n-1) xs
  15.  
  16. takeWhile f [1..]
  17.  
  18. import Data.List
  19.  
  20. data Nat = S Nat | Z deriving (Eq)
  21.  
  22. instance Num Nat where
  23. fromInteger 0 = Z
  24. fromInteger n = S (fromInteger (n - 1))
  25.  
  26. Z + m = m
  27. S n + m = S (n + m)
  28.  
  29. lazyLength :: [a] -> Nat
  30. lazyLength = genericLength
  31.  
  32. main = do
  33. print $ lazyLength [1..] == 100 -- False
  34. print $ lazyLength [1..100] == 100 -- True
  35.  
  36. avg :: [Double] -> [Double]
  37. avg = drop 1 . scanl f 0.0 . zip [0..]
  38. where f avg (n, i) = avg * (dbl n / dbl n') +
  39. i / dbl n' where n' = n+1
  40. dbl = fromInteger
  41.  
  42. *Main> take 10 $ avg [1..]
  43. [1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0]
  44.  
  45. data FList a = Nil | Cons a !(FList a)
  46.  
  47. {-# LANGUAGE GADTs #-}
  48. {-# LANGUAGE DataKinds #-}
  49. {-# LANGUAGE KindSignatures #-}
  50. {-# LANGUAGE ScopedTypeVariables #-}
  51. {-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
  52.  
  53. data Nat = Z | S Nat deriving (Show, Read, Eq, Ord)
  54.  
  55. data Vec :: Nat -> * -> * where
  56. Nil :: Vec 'Z a
  57. Cons :: a -> Vec n a -> Vec ('S n) a
  58.  
  59. instance Functor (Vec n) where
  60. fmap _f Nil = Nil
  61. fmap f (Cons x xs) = Cons (f x) (fmap f xs)
  62.  
  63. data FList :: * -> * where
  64. FList :: Vec n a -> FList a
  65.  
  66. instance Functor FList where
  67. fmap f (FList xs) = FList (fmap f xs)
  68.  
  69. fcons :: a -> FList a -> FList a
  70. fcons x (FList xs) = FList (Cons x xs)
  71.  
  72. funcons :: FList a -> Maybe (a, FList a)
  73. funcons (FList Nil) = Nothing
  74. funcons (FList (Cons x xs)) = Just (x, FList xs)
  75.  
  76. -- Foldable and Traversable instances are straightforward
  77. -- as well, and in recent GHC versions, Foldable brings
  78. -- along a definition of length.
Add Comment
Please, Sign In to add comment