我正在关注这个Haskell tutorial,我在高阶函数部分。它定义了一个函数调用链:Haskell中的嵌套列表解析
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain n
| even n = n:chain (n `div` 2)
| odd n = n:chain (n * 3 + 1)
有一项工作,发现有一个长度大于15长,他们这样做这样的“链”的数量:
numLongChains :: Int
numLongChains = length (filter isLong (map chain [1..100]))
where isLong xs = length xs > 15
我想提出一个列表理解,而不是给我链条的数量给我一个从[1..100]超过15的链列表。我最近尝试到目前为止是这样的:
[ [ a | a <- chain b, length a > 15] | b <- [1..100]]
,但我得到:
<interactive>:9:14:
No instance for (Integral [a0]) arising from a use of `chain'
Possible fix: add an instance declaration for (Integral [a0])
In the expression: chain b
In a stmt of a list comprehension: a <- chain b
In the expression: [a | a <- chain b, length a > 15]
<interactive>:9:45:
No instance for (Enum [a0])
arising from the arithmetic sequence `1 .. 100'
Possible fix: add an instance declaration for (Enum [a0])
In the expression: [1 .. 100]
In a stmt of a list comprehension: b <- [1 .. 100]
In the expression:
[[a | a <- chain b, length a > 15] | b <- [1 .. 100]]
<interactive>:9:46:
No instance for (Num [a0]) arising from the literal `1'
Possible fix: add an instance declaration for (Num [a0])
In the expression: 1
In the expression: [1 .. 100]
In a stmt of a list comprehension: b <- [1 .. 100]
难道我还差得远?尽管可能有更好的方法来解决这个问题,但我仍然想用嵌套理解来解决这个问题。
来到这里的教程完全一样的地方! – 2017-10-13 12:11:28