Skip to content

Instantly share code, notes, and snippets.

@googya
Created December 18, 2017 04:55
Show Gist options
  • Select an option

  • Save googya/bf9952afbcbae4bfe546a774f1600b1f to your computer and use it in GitHub Desktop.

Select an option

Save googya/bf9952afbcbae4bfe546a774f1600b1f to your computer and use it in GitHub Desktop.
module Ex where
newtype Flip f a b =
Flip (f b a)
deriving (Eq, Show)
newtype K a b =
K a
deriving (Eq, Show)
instance Functor (Flip K a) where
fmap f (Flip ( K a )) = Flip $ K (f a)
data EvilGoateeConst a b =
GoatyConst b
deriving (Eq, Show)
instance Functor (EvilGoateeConst a) where
fmap f (GoatyConst b) = GoatyConst (f b)
data LiftItOut f a =
LiftItOut (f a) deriving (Eq, Show)
instance (Functor f) => Functor (LiftItOut f) where
fmap f (LiftItOut g ) = LiftItOut (fmap f g)
data Parappa f g a =
DaWrappa (f a) (g a) deriving (Eq, Show)
instance (Functor f, Functor g) => Functor (Parappa f g) where
fmap f (DaWrappa x y) = DaWrappa (fmap f x) (fmap f y)
data IgnoreOne f g a b =
IgnoringSomething (f a) (g b) deriving (Eq, Show)
instance (Functor f, Functor g) => Functor (IgnoreOne f g a) where
fmap f (IgnoringSomething l m) = IgnoringSomething l (fmap f m)
data Notorious g o a t =
Notorious (g o) (g a) (g t) deriving (Eq, Show)
instance (Functor g) => Functor (Notorious g o a) where
fmap f (Notorious m n q) = Notorious m n (fmap f q)
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor (List) where
fmap _ Nil = Nil
fmap f (Cons a b) = Cons (f a) (fmap f b)
data GoatLoad a =
NoGoat
| OneGoat a
| MoreGoats (GoatLoad a) (GoatLoad a) (GoatLoad a)
deriving (Eq, Show)
instance Functor (GoatLoad) where
fmap _ NoGoat = NoGoat
fmap f (OneGoat a) = OneGoat (f a)
fmap f (MoreGoats m n p) = MoreGoats (fmap f m) (fmap f n) (fmap f p)
@googya

googya commented Jul 8, 2020

Copy link
Copy Markdown
Author
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

takeMyWhile p  = foldr (\a b -> if (p a) then a:b  else []) [1,2,3]  

-- takeMyWhile (> 5) [7, 8, 9, 3] => [7,8,9]

因为 foldr 展开后其实是 x1 f (x2 f ... (xn f z)...) 这种形式, 意味着后续的计算可以提前终止(满足 f) 所以 foldr 可以处理无穷列表

另, 注意结合的方式是 x1 x2 x3 .. z , 所以, 如果计算的时候, 提前终止了, 则 z 根本不参与运算, 给其赋初始值也无意义, 如此例中的 [1,2,3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment