簡體   English   中英

嘗試運行時解析錯誤 haskell function?

[英]Parse error when trying to run haskell function?

我正在嘗試編寫一個使用折疊的 Haskell function 並將采用一個字符串並將其“單詞值”作為一個 int 返回。 這是 function:

import Data.Char

wordValue :: String -> Int
wordValue (x:xs) = foldr (\(ord(toLower x) - (ord 'a') + 1)) 0 xs

基本上,我試圖將每個字符轉換為一個 int 值並使用“foldr”function 來累積該值。 但是,我收到以下錯誤,我不明白:

Parse error in pattern: ord (toLower x) - (ord 'a') + 1

foldr function 也有兩個參數:列表的項目和尾部的foldr的結果。 因此,您應該將其實現為:

wordValue :: String -> Int
wordValue xs = foldr (\x ys -> ord (toLower x) - ord 'a' + ys + 1) 0 xs

其中x是列表的字符, ys是折疊列表的rest的結果(所以剩余元素的wordValue )。

但是在這里使用映射並總結它們更簡單,所以:

wordValue :: String -> Int
wordValue = sum . map (\x -> ord (toLower x) - ord 'a' + 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM