[英]Parse error when trying to run haskell function?
I'm trying to write a Haskell function that uses folds and will take a string and return its "word value" as an int.我正在尝试编写一个使用折叠的 Haskell function 并将采用一个字符串并将其“单词值”作为一个 int 返回。 This is the function:
这是 function:
import Data.Char
wordValue :: String -> Int
wordValue (x:xs) = foldr (\(ord(toLower x) - (ord 'a') + 1)) 0 xs
Basically, i'm trying to convert each character into a int value and use the 'foldr' function to accumulate the value.基本上,我试图将每个字符转换为一个 int 值并使用“foldr”function 来累积该值。 But, I'm getting the following error, which I don't understand:
但是,我收到以下错误,我不明白:
Parse error in pattern: ord (toLower x) - (ord 'a') + 1
The foldr
function also take two parameters: the item of the list, and the result of the foldr
of the tail. foldr
function 也有两个参数:列表的项目和尾部的foldr
的结果。 You thus should implement this as:因此,您应该将其实现为:
wordValue :: String -> Int
wordValue xs = foldr (\x ys -> ord (toLower x) - ord 'a' + ys + 1) 0 xs
where x
is the character of the list, and ys
is the result of folding the rest of the list (so the wordValue
of the remaining elements).其中
x
是列表的字符, ys
是折叠列表的rest的结果(所以剩余元素的wordValue
)。
But here it is simpler to just work with a mapping and summing these up, so:但是在这里使用映射并总结它们更简单,所以:
wordValue :: String -> Int
wordValue = sum . map (\x -> ord (toLower x) - ord 'a' + 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.