Reputation: 21
i'm a beginner in haskell… i'm trying to write a function short:: String -> String that encodes a string with only contains the following characters:
moni :: Char -> String
moni 'm' = "01"
moni 'o' = "1"
moni 'n' = "001"
moni 'i' = "11"
short :: String -> String
short x = moni 'x' -- here i try that short m = "01" but it doesn´t work…. why?)
in ghci:
short m -- error variable not in scope
short "m" -- error Non-exhaustive patterns in function code
In the end the function short should return only a string of bits … example "omi" should yield "10111"....
Upvotes: 1
Views: 62
Reputation: 476574
If you write 'x'
, you do not use the variable x
, you used a character literal.
If you want to "unpack" a string, such that you retrieve the only character, then you can use:
short :: String -> String
short [x] = moni x
since a String
is just a list of Char
s. But the above will not work for a string with no characters, or two or more. If you want to map every character to its moni
equivalent, and concatenate the result, you can use concatMap
:
short :: String -> String
short = concatMap moni
Upvotes: 4