Output all instances from 1 to 8 where the length of the spelling of a number is greater than the length of the spelling of a value higher than it?

时间:2019-03-19 14:57:15

标签: haskell scope ghci

I'm a complete Haskell noob and I've been trying to do this for an entire day now.

So one output could be:

Three,Six

(3 is less than 6 but the spelling of it is longer than the spelling of 6)

I came up with this in Haskell but the variables go out of scope, I don't really understand scope in Haskell yet. This might be completely wrong but any help is appreciated.

let numbers = [("One",1),("Two",2),("Three",3),("Four",4),("Five",5),("Six",6),("Seven",7),("Eight",8)]

[([ x | x <- numbers], [y | y <- numbers]) | length (fst x) > length (fst y), snd x < snd y]

Can someone help me to correct this nested list comprehension? Or even tell me if I can use a nested list comprehension at all?

To clarify:

I want to output a list of pairs, where the spelling of the first element in the pair is longer than the spelling of the second element in the pair, but also, the first element in the pair as a number, is less than the second element in the pair as a number.

1 个答案:

答案 0 :(得分:3)

听起来您想要这样的东西:

[(y1, y2) | (x1, y1) <- numbers, (x2, y2) <- numbers, length x1 > length x2, y1 < y2]

也就是说,它是一对数字对的列表-具有您指定的要求。我暂时无法对此进行测试,我认为它应该可以工作,但是如果您有任何问题,请告诉我。

您的范围问题是因为您试图嵌套理解并从外部的内部理解访问变量-这是不允许的,因为在内部理解中使用的变量仅在特定理解范围内。

>

我还通过对这对元素上的显式模式匹配替换了您对fstsnd的使用,这几乎总是首选,因为它更明确。