利用FlexibleInstances快速推理Num/Fractional

直接上代码:

{-# LANGUAGE FlexibleInstances #-}

module Vector where

import GHC.Base(liftA2)

data Vector2 a = Vector2 a a deriving(Eq, Show, Read)
data Vector3 a = Vector3 a a a deriving(Eq, Show, Read)
data Vector4 a = Vector4 a a a a deriving(Eq, Show, Read)

-- Instances of Functor
instance Functor Vector2 where
    fmap f (Vector2 x y) = Vector2 (f x) (f y)

instance Functor Vector3 where
    fmap f (Vector3 x y z) = Vector3 (f x) (f y) (f z)

instance Functor Vector4 where
    fmap f (Vector4 x y z w) = Vector4 (f x) (f y) (f z) (f w)

-- Instances of Appilcative
instance Applicative Vector2 where
    pure x = Vector2 x x
    liftA2 f (Vector2 x1 y1) (Vector2 x2 y2) = Vector2 (f x1 x2) (f y1 y2)

instance Applicative Vector3 where
    pure x = Vector3 x x x
    liftA2 f (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = Vector3 (f x1 x2) (f y1 y2) (f z1 z2)

instance Applicative Vector4 where
    pure x = Vector4 x x x x
    liftA2 f (Vector4 x1 y1 z1 w1) (Vector4 x2 y2 z2 w2) = Vector4 (f x1 x2) (f y1 y2) (f z1 z2) (f w1 w2)

-- Instances of Num
instance (Applicative f, Num a) => Num (f a) where
    (+) = liftA2 (+)
    (-) = liftA2 (-)
    (*) = liftA2 (*)
    negate = fmap negate
    abs = fmap abs
    signum = fmap signum
    fromInteger = pure . fromInteger

-- Instances of Fractional
instance (Applicative f, Fractional a) => Fractional (f a) where
    (/) = liftA2 (/)
    recip = fmap recip
    fromRational = pure . fromRational

向量化问题以最精简的方式解决。不过由于[]Data.VectorApplicave Instances的行为不太符合向量化的一般意义,所以最好用另外一个类似Applicative的typeclass来替换。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,958评论 2 59
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,032评论 2 89
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,349评论 25 708
  • 原以为车位尘埃落定,没想到有人提出分配不公,要求重分,真是有意思,既然选择抽签就是认命了,又有什么公不公的,而且重...
    紫微妈咪阅读 123评论 0 0
  • 知乎原文链接by张亮原文发布时间:2017年1月5日 俞军产品方法论的三条新总结 用户价值 用户样本量 怀疑精神 ...
    wy_nemo阅读 1,756评论 0 1