haskell Functor

typeclass Functor代表可以被 map over 的事物。List, Maybe 都是Functor. 需要是一个参数的类型构造子或函数。 

  需要满足functor law:(满足定理的好处, 用定律来推论类型的行为, 不用看 fmap 的实现)

  •  如果我们对 functor 做 map id,那得到的新的 functor 应该要跟原来的一样。如果写得正式一点,他代表 fmap id = id
  • 先将两个函数合成并将结果 map over 一个 functor 的结果,应该跟先将第一个函数 map over 一个 functor,
    再将第二个函数 map over 那个 functor 的结果是一样的。
    正式地写下来的话就是fmap (f . g) = fmap f . fmap g
    (或 fmap (f . g) F = fmap f (fmap g F))

class Functor f where 
    fmap :: (a -> b) -> f a -> f b
instance Functor [] where 
    fmap = map
instance Functor Maybe where 
    fmap f (Just x) = Just (f x) 
    fmap f Nothing = Nothing
data Either a b = Left a | Right b

instance Functor (Either a) where 
    fmap f (Right x) = Right (f x) 
    fmap f (Left x) = Left x

instance Functor ((->) r) where   
    fmap f g = (\x -> f (g x))
instance Functor ((->) r) where   
    fmap = (.)
fmap :: (a -> b) -> (r -> a) -> (r -> b)


说明;如果一个 type constructor 要是  Functor  的 instance,那他的 kind 必须是  * -> * ,这代表他必须刚好接受一个 type 当作 type parameter。像是  Maybe  可以是 Functor 的一个 instance,因为他接受一个 type parameter,来做成像是  Maybe Int ,或是  Maybe String 。如果一个 type constructor 接受两个参数,像是  Either ,我们必须给他两个 type parameter。所以我们不能这样写: instance Functor Either where ,但我们可以写  instance Functor (Either a) where ,如果我们把  fmap  限缩成只是  Either a  的,那他的型态就是 fmap :: (b -> c) -> Either a b -> Either a c

      对于是一个参数的函数的类型: (->) r  是描述类型。 原来看到 (*3), 一直以为 r是需要在输入的参数,是不对的。(->) 的Kind 如下,是一个两个参数的运算符。  (->) r  是一个整体, 表示 (->) 已经接受一个参数, 他的Kind 应该是  *-> * 的类型。

> :k (->)
(->) :: * -> * -> *


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值