简体   繁体   English

尝试运行时解析错误 haskell function?

[英]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.

相关问题 尝试将字符串解析为int时出错 - Error when trying to parse a string as an int Haskell - 尝试将函数应用于多个数字的行 - Haskell - Trying to apply a function to lines of multiple numbers 尝试从函数返回字符串时,“str”对象不可调用错误 - 'str' object is not callable error when trying to return a string from a function 连接字符串时Haskell中的词汇错误 - Lexical error in Haskell when concatenating strings 尝试运行时显示的消息 - message displayed when trying to run 为什么在尝试将字符串添加到此字符串末尾时haskell会停止? - Why does haskell stop when trying to add a string to the end of this string? 尝试解析csv文件时声明错误 - Errors in declaration when trying to parse a csv file 尝试从.getText()解析字符串时出现NumberFormatException; - NumberFormatException when trying to parse Strings from .getText(); 从字符串运行函数并解析变量? - Run function from string and parse variable? 当我尝试在代码块编译器中运行此程序时,strstr()函数每次都返回0。 为什么? - When I was trying to run this program in the codeblocks compiler, the strstr() function was returning 0 everytime. Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM