Search code examples
dictionaryhaskelltuplesencodetranslate

How can I translate a String to another String using a given dictionary list in Haskell?


I've made a list of tuples:

dic = zip(['a' .. 'z') (['o' .. ])

It should work to infinite list too, so I was thinking I can't use recursion or list comprehension. Then what? :D The result should be something like this:

dic :: [Char] -> [Char]
dic "abc" = "opq"

Solution

  • First of all, you should wrap back from 'z' to 'a', so your dic would look something like:

    dic :: [(Char, Char)]
    dic = zip ['a'..'z'] (['o'..'z'] ++ ['a'..])
    

    Now, you can just look up the characters from the list:

    func :: [Char] -> [Char]
    func = map (\x ->
        case lookup x dic of
            Just v -> v
            otherwise -> x)
    

    Or, with fromMaybe from Data.Maybe:

    import Data.Maybe
    
    func :: [Char] -> [Char]
    func = map (\x -> fromMaybe x $ lookup x dic)
    

    This works (along with recursive/list comprehension solutions) with infinite char lists due to lazy evaluation: if a value isn't used, then it isn't calculated.