Here is a little look on how the dictionary program is built
dictionary = [
("thanks",["danke"]),
("always",["immer"]),
("us", ["uns"])
]
as u can see from the dictionary the strings comes in pair of
(string, [string])
Here is a little look on how the dictionary program is built
dictionary = [
("thanks",["danke"]),
("always",["immer"]),
("us", ["uns"])
]
as u can see from the dictionary the strings comes in pair of
(string, [string])
I have been given a dictionary in form of a skeleton program
No, you have been given a dictionary
dictionary :: [(String, [String])]
dictionary = [
("thanks",["danke"]),
("always",["immer"]),
("us", ["uns"])
]
and a type signature
translate :: String -> String
There isn't really any “skeleton” here, but you might call the following a skeleton of translate
:
translate (x:xs) = _
What this would do is, try to select a suitable element from the dictionary for the start of the input. However, we're already on the wrong course because this start of the input x
is just the first letter, whereas to match in the dictionary you need a whole word.
Fortunately, Haskell comes with a helper function to obtain the words in a given string, sensibly called words
. So it would make sense to apply this to the input string, and then translate each word separately:
translate xs = translateWords (words xs)
translateWords :: [String] -> String
translateWords = _
or, if each word is supposed to be translated to a single other word,
translate = unwords . map translateWord . words
translateWord :: String -> String
translateWord = _
Here you don't need to worry about deconstructing a word further – there's nothing you could do with the individual letters. Instead, just make it
translateWord w = _
Now you could attempt matching the word w
in the dictionary. Paraphrasing your attempt,
translateWord w
| w`elem`dictionary = y
| otherwise = " "
But what is y
now? And the types don't match for this use of elem
: that would require dictionary
to be just a list of words, not of tuples.
So, what you need is a tool that doesn't just tell you whether an element is in a list, but rather whether it's in the first tuple-part of an element of the list, as well as what the other half of that tuple is. In other words, you're looking for a function of the signature
searchMatch :: a -> [(a,b)] -> b
Well, that's something you can ask Hoogle about. It gives one match in the base
library:
lookup :: Eq a => a -> [(a, b)] -> Maybe b
The Maybe
is responsible for telling you whether a match was found at all. You can pattern-match on it:
translateWord w = case lookup w dictionary of
Just wTranslations -> _
Nothing -> " "
Now the remaining _
you should try to fill out yourself.
You have been given a dictionary, to translate an input string, recursively compare every element in the second element of the head of the dictionary, to your input string.