懒惰和功能组成(haskell,erlang) [英] laziness and function composition (haskell, erlang)

查看:97
本文介绍了懒惰和功能组成(haskell,erlang)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释或提供一些关于惰性的功能组合如何工作的信息吗?

Can someone please explain or give some resources on how function composition works in relation to laziness?

例如如何过滤(/ = 'W')。将Haskell中的toupper $ justaword 映射到与不是懒惰的erlang中的对应项相比?

For example how does filter (/='W') . map toUpper $ "justaword" work in Haskell compared to it's counterpart in erlang which is not lazy?

推荐答案

每当要求另一个字符(或结束通知)时,下一个字符(如果有的话)都映射为大写字母,与不等号的 W进行比较。

Every time another character is demanded (or notification of end), the next character - if any - is mapped to uppercase, that is compared to 'W', delivered if unequal.

filter (/= 'W') . map toUpper $ "justaword"
~> filter (/= 'W') (toUpper 'j' : map toUpper "ustaword")
~> filter (/= 'W') ('J' : map toUpper "ustaword")
~> 'J' : filter (/= 'W') (map toUpper "ustaword")

现在首字符可用,因此对于诸如 null 之类的查询或诸如 take 1 之类的函数,无需进行进一步的工作。如果消费者需要更多字符,它们将被一一制作,直到到达字符串的末尾。

Now the first character is available, so for queries like null or functions like take 1, no further work is done. If more characters are demanded by the consumer, they will be produced one by one until the end of the string is reached.

示例:

Prelude Data.Char> take 10 . filter (/= 'W') . map toUpper $ repeat 't'
"TTTTTTTTTT"

重复产生一个无限列表,但是只要只消耗一个有限的部分,计算就会在有限的时间内完成。但是,取10。过滤器(/ ='W')。映射到上层$重复'w'不会终止,因为所有产生的字符都不通过过滤器达到 10

repeat produces an infinite list, but as long as only a finite part is consumed, the computation finishes in finite time. However, take 10 . filter (/= 'W') . map toUpper $ repeat 'w' would not terminate, since none of the produced characters passes the filter to reach the take 10.

这篇关于懒惰和功能组成(haskell,erlang)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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