繁体   English   中英

Haskell中的嵌套列表推导

[英]Nested list comprehensions in Haskell

我正在关注此Haskell教程,并且位于“高阶函数”部分。 它定义一个名为chain的函数为:

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]

我什至靠近吗? 我确实想通过嵌套理解来解决这个问题,尽管可能有更好的方法来学习。

你近了 您正在寻找:

[ a | b <- [1..10], let a = chain b, length a > 15 ]

表达方式

[ [ a | a <- chain b, length a > 15] | b <- [1..100]]

具有类型:

Integral [a] => [[[a]]]

这显然不是您想要的,但是由于Haskell的多态数字文字,它可能可以键入检查是否有正确的定义。

在这种情况下, b被推断为某种类型的列表,这就是为什么您看到错误的原因:

No instance for (Integral [a0]) ...

这是有关如何推断类型的完整总结。

  1. b <- [1..100]我们可以推断Enum b是一个约束
  2. 从调用chain b可以推断出Integral b是一个约束
  3. a <- chain b可以推断出ab具有相同的类型
  4. length a我们可以推断出a是某物的列表,例如a ~ [t]

因此,从(3)和(4)我们可以推断出b〜 b ~ [t] ,因此对于某些类型t ,我们需要Integral [t]Enum [t]

为了进一步阐述(3),我们知道chain b是一个列表,例如[t] ,其中tb的类型。 a <- chain b ,我们知道a具有相同类型的元素chain b ,即类型at

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM