Distributive

class Functor g => Distributive g where
distribute :: Functor f => f (g a) -> g (f a)
distribute = collect id collect :: Functor f => (a -> g b) -> f a -> g (f b)
collect f = distribute . fmap f distributeM :: Monad m => m (g a) -> g (m a)
distributeM = fmap unwrapMonad . distribute . WrapMonad collectM :: Monad m => (a -> g b) -> m a -> g (m b)
collectM f = distributeM . liftM f cotraverse :: (Distributive g, Functor f) => (f a -> b) -> f (g a) -> g b
cotraverse f = fmap f . distribute comapM :: (Distributive g, Monad m) => (m a -> b) -> m (g a) -> g b
comapM f = fmap f . distributeM

Distributive 是个类型类。功能上与 Traversable 类型类呈现对偶(dual)关系。

Traversable 类型将一个函数应用到多个数值,而

Distributive 类型将一个数值应用到多个函数。

((->)e) 是个 Distributive

instance Distributive ((->)e) where
distribute a e = fmap ($e) a
collect f q e = fmap (flip f e) q

Sum 是个 Distributive

instance Distributive Monoid.Sum where
collect = coerce (fmap :: (a -> b) -> f a -> f b)
:: forall f a b . Functor f
=> (a -> Monoid.Sum b) -> f a -> Monoid.Sum (f b)
distribute = Monoid.Sum . fmap Monoid.getSum

应用 Distributive

Prelude Data.Distributive> distribute [(+1),(+2)] 1
[2,3]
Prelude Data.Distributive> collect (^) [1,2] 3
[1,8]
Prelude Data.Distributive> cotraverse sum [(+1),(*2)] 3
10
Prelude Data.Distributive> comapM product [(+1),(*2)] 3
24
Prelude Data.Distributive Data.Monoid> distribute [Sum 1, Sum 2]
Sum {getSum = [1,2]}
Prelude Data.Distributive Data.Monoid> collect (\x->Sum[x]) [3,4]
Sum {getSum = [[3],[4]]}

手动计算

distribute [(+1),(+2)] 1
= fmap ($1) [(+1),(+2)]
= [1+1,1+2] = [2,3]
collect (^) [1,2] 3
= fmap (flip (^) 3) [1,2]
= fmap (^3) [1,2]
= [1^3,2^3] = [1,8]
cotraverse sum [(+1),(*2)] 3
= (fmap sum . distribute) [(+1),(*2)] 3
= sum $ distribute [(+1),(*2)] 3
= sum [4, 6] = 10 这里
(fmap f . g) x y
= (f . g x) y
= f $ g x y

最新文章

  1. arcgis api for js入门开发系列三地图工具栏(含源代码)
  2. Android Studio Jni 环境搭建
  3. 解决VML遭遇IE8和XHTML DOCTYPE时不能运行的问题(转)
  4. 3.SpringMVC修改配置文件路径和给界面传递数据
  5. C#基础——谈谈.NET异步编程的演变史
  6. codeforces 489A.SwapSort 解题报告
  7. ASP.NET MVC3 系列教程 – Web Pages 1.0
  8. 批处理DataTable
  9. epub3 in action: epub3文件格式简介
  10. poj1286
  11. CentOS 6.5系统安装配置图解教程(详细图文)
  12. XML实例文档
  13. centos7防火墙配置
  14. Mail.Ru Cup 2018 Round 2
  15. linux防火墙,高级策略策略实例详解(实例一)
  16. Android AlertDialog 绝对位置计算
  17. margin塌陷
  18. ADO.NET目录汇总1
  19. SQL Support and Workarounds
  20. Toad 实现 SQL 优化

热门文章

  1. Navicat导出opencart2.3数据字典
  2. dubbo实战
  3. 如何使用swingbench进行oracle数据库压力测试
  4. linux下syscall函数 间接系统调用
  5. ios获取安装的app
  6. SpringCloud使用jpa之传统方式
  7. Nginx+tomcat+redis实现session共享
  8. Linux故障-bash-4.1$
  9. Linux 简单命令查询CPU、内存、网卡等信息
  10. asp控制项目超时