嘿伙计们,所以我想要一个单词列表并返回一个类似的列表但是 每次出现连续单词时都会进行以下替换。
一个例子是you
并将其转换为u
我给出了以下内容:
hep :: [Word] -> [Word]
type Word = String
现在给我的问题是我正在尝试使用case表达式,这样我就不必重复代码了但是我得到以下错误
Couldn't match expected type `Char' with actual type `[Char]'
In the pattern: "You"
In a case alternative: "You" -> "u" : hep xs
In the expression: case a of { "You" -> "u" : hep xs }
来自以下代码
hep [] = []
hep [a:xs] = case a of
"You" -> "u":hep xs
有人告诉我这是什么问题吗?
编辑:
我添加了以下代码
hep [] = [[]]
hep (a:xs) = case a of
"you" -> "u":hep xs
"are" -> "r":hep xs
"your" -> "ur":hep xs
"boyfriend" -> "bf":hep xs
"girlfriend" -> "gf":hep xs
"great" -> "gr8":hep xs
a -> a:hep xs
现在我如何能够添加案例,以便如果列表中包含2或3个特定单词,我可以将其转换为首字母缩略词?
实施例
["By","The","way"] = ["btw"]
答案 0 :(得分:3)
您尝试匹配字符串列表的列表,但hep
的类型为[Word] -> [Word]
,这与此相矛盾。错误消息指的是这个事实。
但我猜你真正想要的是这个吗?
hep [] = []
hep (a:xs) = case a of
"You" -> "u":hep xs
a -> a:hep xs
答案 1 :(得分:0)
这样的东西?
"By" -> let (y:ys) = xs
in if y=="The" && head ys=="Way"
then "btw": hep (drop 2 xs)
else a:hep xs
虽然我不想连续写50次。怎么样?
import Data.List
import Data.Maybe
hep [] = []
hep (a:xs) = case a of
"you" -> "u":hep xs
"are" -> "r":hep xs
"your" -> "ur":hep xs
"boyfriend" -> "bf":hep xs
"girlfriend" -> "gf":hep xs
"great" -> "gr8":hep xs
"by" -> matchPhrase 3
"see" -> matchPhrase 2
a -> a:hep xs
where matchPhrase num =
let found = lookup (concat $ take num (a:xs)) phrase_list
in case found of
Just _ -> fromJust found : hep (drop num (a:xs))
Nothing -> a:hep xs
phrase_list = [("bytheway", "btw"), ("seeyou","cu")]