我最近开始学习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]] 。 谢谢!
答案 0 :(得分:4)
问题是vocal
有类型:
vocal :: String -> Bool
这是因为 因此Haskell得出的结论是,因为您致电 我们可以轻松地将其改为: 或更短: 话虽这么说,你的代码非常混乱。我们可以将其重写为: 行 我们想要的是致电vocals
是String
的列表,因此elem
会检查字符串是否在字符串列表中。< / p>
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
作为输入,它接受两个参数x
和y
。然后它将它变成一个带有两个参数y
和x
的函数(因此参数被翻转)。elem o vocals
。这相当于flip elem vocals o
。现在通过使用 eta -reduction,我们可以省略o
(在子句的头部和主体中)。