目前,我正在尝试将几个项目转换为classy-prelude。虽然大多数行为在我看来都很简单,但(head . head)在一个简单的2D列表上却给出了神秘的错误。
考虑以下GHCi会话:
Prelude> (head . head) [[1,2],[3,4]]
1让我们用ghci -XNoImplicitPrelude和classy-prelude来试试这个
> import ClassyPrelude
ClassyPrelude> (head . head) [[1,2],[3,4]]
<interactive>:10:1:
Couldn't match type `MinLen (Succ nat1) mono1' with `[[t0]]'
Expected type: [[t0]] -> Element mono0
Actual type: MinLen (Succ nat1) mono1 -> Element mono0
The function `head . head' is applied to one argument,
but its type `MinLen (Succ nat1) mono1 -> Element mono0'
has only one
In the expression: (head . head) [[1, 2], [3, 4]]
In an equation for `it': it = (head . head) [[1, 2], [3, 4]]我认为GHC根本无法正确解析多维列表的类型。我有没有办法不求助于(Prelude.head . Prelude.head)
发布于 2014-02-26 00:42:28
正如注释中已经提到的,经典前奏的head函数只适用于可遍历的,这些可遍历的类型系统至少有一个元素,因此它不必是部分的。由于所有列表中至少有一个元素,所以只需使用非空列表类型:
head . head $ mlcons (mlcons 1 $ mlcons 2 $ toMinLenZero []) $ mlcons (mlcons 3 $ mlcons 4 $ toMinLenZero []) $ toMinLenZero [] :: Int
-- 1(以ml开头的函数都来自mono-traversable的MinLen模块,该模块由classy-prelude重新导出)
如果只想要Prelude.head函数的行为,可以从mono-traversable包中再次使用unsafeHead,并默认情况下导出:
unsafeHead . unsafeHead [[1,2],[3,4]]
-- 1该模块中也有headMay,如果您希望以不同的方式处理故障而不让整个程序崩溃,则可以使用该模块。
https://stackoverflow.com/questions/22027975
复制相似问题