haskell - let /在列表理解中等价吗? [英] haskell - let/where equivalent within list comprehension?

查看:126
本文介绍了haskell - let /在列表理解中等价吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 let where 或以其他方式在列表理解中定义子表达式,以便它可以用于术语和约束?

Is there a way to use let,where or otherwise define sub-expressions in a list comprehension so that it can be used both in the term and constraint?

从我的试验中,以下工作:

From my experimenting, the following work:

[let x = i*i in x | i<-[1..10], i*i > 20]   --good
[i*i | i<-[1..10], let x=i*i in x > 20]     --good

但是这些不是范围的BC:

But these do not bc of scope:

[let x = i*i in x | i<-[1..10], x > 20]  -- 'x' not in scope error
let x = i*i in [x | i<-[1..10], x > 20]  -- 'i' not in scope error
[x | i<-[1..10], x > 20] where x = i*i   --parse error on 'where'

所以让可以在一个地方或另一个地方工作,但不能同时在一起!

So let works in one place or the other, but not both together!

我发现使它工作的唯一方法也就是说,避免重复的表达和可能的评估)就像我在这里用 x < - [cat i [1..k] 作为一个单词列表添加一个愚蠢的单例列表限制列表理解:

The only way I've found to make it work (that is, avoid repeated expressions and possibly evaluations) is to add a silly singleton-list as I did here with x<-[cat i [1..k] as a constraint to the list comprehension:

> let cat x l = foldl1 (++) $ map show [x*i | i<-l]
maximum [x| i<-[1..9999], k<-[2..div 10 $ length $ show i], x<-[cat i [1..k]], sort x == "123456789"]
"932718654"

或者,包含上面的小例子,

Or, contunuing the trivial example above,

[x | i<-[0..10], x<-[i*i], x > 20] --works

这看起来有点愚蠢,并且略微缺乏清晰度,看起来太低效了。不过,如果 let 其中在整个理解中起作用,那将会很好。可以这样做吗?

This seems a little silly, and is slightly lacking in clarity, tho it doesn't seem too inefficient. Still, it would be nice if let or where worked across the whole comprehension. Can this be done?

推荐答案

您可以这样写:

You write it like this:

[x | i <- [0..10], let x = i*i, x > 20]

注意中没有。您可以在术语中引用 x ,也可以在 let 之后的任何约束。这种形式的 let 对应于 do -notation中的那个:

Notice there is no in. You can refer to x in both the term, and any constraints following the let. This form of let corresponds to the one in do-notation:

do i <- [0..10]
   let x = i*i
   guard (x > 20)
   return x

这里 x 让到 do - 块的结尾。

Here x is in scope from the let to the end of the do-block.

这篇关于haskell - let /在列表理解中等价吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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