此代码编译:
import Data.List (isPrefixOf)
import Data.Monoid (Any(..))
import Data.Coerce
isRoot :: String -> Bool
isRoot path = getAny $ foldMap (coerce . isPrefixOf) ["src", "lib"] $ path
我coerce
用作包装 in 最终结果的快捷isPrefixOf
方式Any
。
这个类似的代码无法编译(注意缺少.
):
isRoot :: String -> Bool
isRoot path = getAny $ foldMap (coerce isPrefixOf) ["src", "lib"] $ path
错误是:
* Couldn't match representation of type `a0' with that of `Char'
arising from a use of `coerce'
* In the first argument of `foldMap', namely `(coerce isPrefixOf)'
In the first argument of `($)', namely
`foldMap (coerce isPrefixOf) ["src", "lib"]'
In the second argument of `($)', namely
`foldMap (coerce isPrefixOf) ["src", "lib"] $ path'
但我的直觉是它也应该编译。毕竟,我们知道isPrefixOf
will 的参数是String
s,并且结果必须是类型Any
。没有歧义。所以String -> String -> Bool
应该转换为String -> String -> Any
. 为什么它不起作用?