Hey guys so I'm suppose to takes a list of words and returns a list just like it but with the following substitutions made each time they appear as consecutive words.
One example is you
and turn it into u
I'm given the following:
hep :: [Word] -> [Word]
type Word = String
now what is giving me problem is that I'm trying to use case expressions so that I won't have to repeat code but I get the following error
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 }
from the following code
hep [] = []
hep [a:xs] = case a of
"You" -> "u":hep xs
Anyone tell me what the problem is?
Edit:
I have added the following code
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
Now how would I be able to add a case so that if the list contains 2 or 3 certain words in an order, I could turn that into an acronym?
Ex
["By","The","way"] = ["btw"]
You're trying to match against a list of a list of Strings, but the type of hep
is [Word] -> [Word]
, which contradicts that. The error message is referring to this fact.
But I'm guessing what you actually want is this?
hep [] = []
hep (a:xs) = case a of
"You" -> "u":hep xs
a -> a:hep xs
Something like this?
"By" -> let (y:ys) = xs
in if y=="The" && head ys=="Way"
then "btw": hep (drop 2 xs)
else a:hep xs
Although I wouldn't want to write that 50 times in a row. How about this?
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")]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.