How to convert a String to lowercase using lambda expressions

William picture William · Oct 20, 2016 · Viewed 10.1k times · Source

I want to know how to convert a string to lowercase using the ToLower function (Char -> Char).

This is the code I have so far:

let newlist = (\(h:t) -> c (h) ++ newlist (\c -> toLower c)

I can't see how to do it without using recursion, which I don't know how to use in a lambda expression

Answer

mnoronha picture mnoronha · Oct 20, 2016

It would be easier to not use a lambda expression considering you can eta-reduce to not explicitly name the variable your function accepts. For example you could use a list comprehension:

import Data.Char

lowerString str = [ toLower loweredString | loweredString <- str]

Which you would call as:

ghci> lowerString "Hello"
hello

Alternatively, you could use map:

lowerString = map toLower

If you insist on using a lambda expression, it would look something like this:

import Data.Char

lowerString = \x -> map toLower x

Which again, is not as nice.