【问题标题】:Haskell Couldn't match expected type ‘[(Char, b0)]’ with actual type ‘(Char, Int)’Haskell 无法将预期类型“[(Char,b0)]”与实际类型“(Char,Int)”匹配
【发布时间】:2015-06-08 13:44:10
【问题描述】:

所以我得到了这段代码,它在预期类型上返回错误。

无法匹配预期类型“[(Char, b0)]”
实际类型为“(Char, Int)”
在表达式中:newList
在列表理解中: (a, b)

我想找回角色的位置,所以应该是'b'。我只是不明白为什么它会给我一个类型错误。每当我在 WinGHCI 中一一运行代码时,我都会得到正确的信息。将其放入 .hs 文件时,它不会。

word = "apple"
isPart :: Char -> a
isPart x = do
            newList <- zip word [0..length word]
            result <- [b | (a,b) <- newList, a == x]
            return result

【问题讨论】:

    标签: haskell


    【解决方案1】:

    在您的 do 块内

    newList <- zip word [0..length word]
    

    被脱糖成类似的东西

    zip word [0..length] >>= \newList -> ...
    

    &gt;&gt;= 的类型是(Monad m) =&gt; m a -&gt; (a -&gt; m b) -&gt; m b

    由于zip 返回一个列表,您正在使用列表monad,因此newList 的类型实际上是(Int, Char)。然后,您不能将其用作后续列表理解的来源。

    但是你根本不需要使用do

    isPart :: Char -> Int
    isPart x = let newList = zip word [0..length word]
                   result = [b | (a,b) <- newList, a == x]
               in  head result
    

    但请注意,如果给定字符不在word 中,这将引发错误

    你也可以更简单地写成

    import Data.List (elemIndex)
    import Data.Maybe (fromJust)
    
    isPart x = fromJust $ elemIndex x word
    

    虽然更好的解决方案是将返回类型更改为Maybe Int,而不是使用fromJust

    【讨论】:

      猜你喜欢
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      相关资源
      最近更新 更多