为什么这两个等价物? [英] Why are this two equivalents?

查看:77
本文介绍了为什么这两个等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太明白为什么要给出两个列表xss :: [[a]]yss :: [[a]]

I don't quite understand why given two list of lists xss :: [[a]] and yss :: [[a]]

liftA2 (++) xss yss

等同于

[xs ++ ys | xs <- xss, ys <- yss]

推荐答案

原因是 liftA2定义是一种优化,我们也可以使用默认定义liftA2手动进行:

The liftA2 definition is an optimization, and we could also do it manually with the default definition of liftA2:

liftA2 f x y = f <$> x <*> y

所以

liftA2 (++) xs ys
   = (++) <$> xs <*> ys
   = fmap (++) xs <*> ys                  -- definition of <$> 
   = [ f y | f <- fmap (++) xs, y <- ys ] -- definition of <*> above
   = [ (++) x y | x <- xs, y <- ys ]      -- some law about fmap/bind
   = [ x ++ y | x <- xs, y <- ys ]

那里有.

关于fmap/bind的一些法律"是这样的:

"Some law about fmap/bind" is this one:

fmap f x >>= t = x >>= t . f

,如果您了解如何理解列表推导,则适用.证据是:

which applies if you understand how list comprehensions are desugared. The proof is:


fmap f x >>= t
    = x >>= pure . f >>= t             -- fmap = liftM coherence
    = x >>= (\y -> pure (f y) >>= t)   -- definition of (.)
    = x >>= (\y -> t (f y))            -- left unit monad law
    = x >>= t . f                      -- definition of (.)

这篇关于为什么这两个等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆