Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a list of strings lowercase in Haskell

I have a list of strings ["Hi", "hELLO", "nO"]

and I want to convert everything to lowercase. I wrote a function for this:

import Data.Char(toLower)
makeSmall xs = map toLower xs

It compiles, but when I do makeSmall ["Hi", "hELLO", "nO"] it gives me this error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<interactive>:2:12: error:
    • Couldn't match expected type ‘Char’ with actual type ‘[Char]’
    • In the expression: "Hi"
      In the first argument of ‘makeSmall’, namely
        ‘["Hi", "hELLO", "nO"]’
      In the expression: makeSmall ["Hi", "hELLO", "nO"]

<interactive>:2:17: error:
    • Couldn't match expected type ‘Char’ with actual type ‘[Char]’
    • In the expression: "hELLO"
      In the first argument of ‘makeSmall’, namely
        ‘["Hi", "hELLO", "nO"]’
      In the expression: makeSmall ["Hi", "hELLO", "nO"]

<interactive>:2:25: error:
    • Couldn't match expected type ‘Char’ with actual type ‘[Char]’
    • In the expression: "nO"
      In the first argument of ‘makeSmall’, namely
        ‘["Hi", "hELLO", "nO"]’
      In the expression: makeSmall ["Hi", "hELLO", "nO"] 

I’m trying to understand how I can make my function work for a list of strings, instead of just a string

>Solution :

toLower :: Char -> Char maps a Char to a Char, this means that map toLower will take a single String, and it will return a String.

If you want to handle a list of Strings, you should use a second map:

makeSmall :: [String] -> [String]
makeSmall xs = map (map toLower) xs

or shorter:

makeSmall :: [String] -> [String]
makeSmall = map (map toLower)

We thus make a mapper that uses map toLower as map function. This function will thus work on a single String. Since we make thus a mapper for this, we work on a list of Strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading