Haskell:预期类型:[Char]实际类型:[[Char]]

时间:2017-07-14 11:05:21

标签: haskell

我最近开始学习Haskell,在我的程序中,我收到以下错误:

    Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [Char]
  Actual type: [[Char]]
In the first argument of ‘head’, namely ‘input’
In the first argument of ‘magi’, namely ‘(head input)’

我的代码如下所示:

vocals = ["a", "e", "i", "o", "u","y"]
vocal o
  | elem o vocals == True = True --return true if the letter is a vowel
  | elem o vocals == False = False --else false

magi konsonant = [konsonant] ++ "o" ++ [konsonant]

rovarsprak input
  |length input == 0 = ""
  |length input > 0 && vocal (head input) == False = magi (head input) ++ rovarsprak (tail input)
  |length input > 0 && vocal (head input) == True = head input : rovarsprak (tail input)

据我所知,我收到错误是因为我对head函数的输入是[[char]]而不是[char],但是我不明白为什么head的输入是[[char]] 。 谢谢!

1 个答案:

答案 0 :(得分:4)

问题是vocal有类型:

vocal :: String -> Bool

这是因为vocalsString列表,因此elem会检查字符串是否在字符串列表中。< / p>

因此Haskell得出的结论是,因为您致电vocal (head input)input本身应该是String的列表。

我们可以轻松地将其改为:

vocals = ['a', 'e', 'i', 'o', 'u', 'y']

或更短:

vocals = "aeiouy"

话虽这么说,你的代码非常混乱。我们可以将其重写为:

vocals :: [Char]
vocals = "aeiouy"

vocal :: Char -> Bool
vocal = flip elem vocals                   -- pointfree function

magi :: Char -> String
magi konsonant = konsonant : 'o' : [konsonant]

rovarsprak :: String -> String
rovarsprak "" = ""                         -- use patterns
rovarsprak (h:t)                           -- use patterns to unpack
    | vocal h = h : rovarsprak t           -- == True is not necessary
    | otherwise = magi h ++ rovarsprak t   -- use otherwise

vocal = flip elem vocals的工作原理如下:flip将一个函数f作为输入,它接受两个参数xy。然后它将它变成一个带有两个参数yx的函数(因此参数被翻转)。

我们想要的是致电elem o vocals。这相当于flip elem vocals o。现在通过使用 eta -reduction,我们可以省略o(在子句的头部和主体中)。