|
| 1 | +-- RWH Chapter 4. Functional programming -- |
| 2 | + |
| 3 | +import Control.Exception (assert) |
| 4 | + |
| 5 | +-- Better to use `null' than `length', because of the lazy evaluation |
| 6 | +-- Or, pattern matching is also a good idea (which actually resembles |
| 7 | +-- what `null' does, so less readable) |
| 8 | +-- This sucks on infinite lists, also decrease performance on long lists |
| 9 | +safeHeadDumb xs = if length xs > 0 |
| 10 | + then Just $ head xs |
| 11 | + else Nothing |
| 12 | +safeHead xs |
| 13 | + | null xs = Nothing |
| 14 | + | otherwise = Just $ head xs |
| 15 | +safeHead' [] = Nothing |
| 16 | +safeHead' xs = Just $ head xs |
| 17 | + |
| 18 | +-- Partial / total functions (think of `totality' in Idris) |
| 19 | + |
| 20 | +-- `and', `or', `all', `any' on empty list |
| 21 | +-- Be careful! Assertion is done when you need its value! |
| 22 | +andEmpty = assert (and []) True |
| 23 | +orEmpty = assert (not $ or []) False |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +-- Failed to get a reasonably working `zipWithN' |
| 28 | +-- Further readings: |
| 29 | +-- * http://okmij.org/ftp/Haskell/polyvariadic.html |
| 30 | +-- * https://stackoverflow.com/questions/20558648/what-is-the-datakinds-extension-of-haskell |
| 31 | +-- * https://www.reddit.com/r/haskell/comments/b9qyp/generalized_zipwithn_with_a_pretty_implementation/ |
| 32 | + |
| 33 | +{- |
| 34 | +--data Z |
| 35 | +--data S n |
| 36 | +
|
| 37 | +class NatureNum a where |
| 38 | + fromNum :: Integral b => b -> a |
| 39 | + toNum :: Integral b => a -> b |
| 40 | +
|
| 41 | +--data Nat n where |
| 42 | +-- Zero :: Nat Z |
| 43 | +-- Succ :: Nat n -> Nat (S n) |
| 44 | +data Nat = Z | S Nat |
| 45 | +
|
| 46 | +--instance NatureNum (Nat) where |
| 47 | +-- toNum Z = 0 |
| 48 | +-- toNum (S n) = 1 + toNum n |
| 49 | +
|
| 50 | +--instance NatureNum Zero where |
| 51 | +-- fromNum _ = Zero |
| 52 | +-- toNum _ = 0 |
| 53 | +--instance NatureNum (Succ n) where |
| 54 | +-- fromNum _ = Succ Zero |
| 55 | +-- toNum _ = 1 |
| 56 | +
|
| 57 | +--fromNum :: Integral a => a -> (Nat n) |
| 58 | +--fromNum 0 = Zero |
| 59 | +----fromNum k = Succ ( fromNum (k-1)) |
| 60 | +--fromNum 1 = Succ Zero |
| 61 | +
|
| 62 | +
|
| 63 | +--data NArgsFunc a :: Nat -> * where |
| 64 | +-- NArgsFunc :: |
| 65 | +
|
| 66 | +--data NArgsFunc a = ZeroArgFunc a |
| 67 | +-- | NArgsFunc a (NArgsFunc a) |
| 68 | +
|
| 69 | +type ZeroArgFunc a = a |
| 70 | +testZ :: (ZeroArgFunc Int) |
| 71 | +testZ = (42) |
| 72 | +type NArgsFunc Nat a = a -> (NArgsFunc Z |
| 73 | +test1 :: (NArgsFunc [Char] (ZeroArgFunc Int)) |
| 74 | +test1 = length |
| 75 | +-} |
0 commit comments