Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to lowercase using lambda expressions

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

like image 809
William Avatar asked Oct 20 '16 01:10

William


Video Answer


2 Answers

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.

like image 144
mnoronha Avatar answered Sep 27 '22 20:09

mnoronha


With a lambda expression you'd still need to recursively check each character of the string, or you could use map which is still a recursive function that applies the function (a -> b) to every element in the list, for example:

  newList [] = []
  newList xs = (\(y:ys) -> if x `elem` ['A'..'Z'] then toLower y : newList ys else y : newList ys) xs

With map is actually much simpler due to reasons explained in the first paragraph, check mnoronha's answer as he already gave you the answer, but that's if you're thinking of using map in conjunction with toLower.

This is an example without a lambda expression, which requires you to import 2 functions from Data.Char, recursively check the rest of the string and replace each character with its lower case version.

newList :: String -> String
newList [] = []
newList (x:xs) = if x `elem` ['A'..'Z'] 
               then chr (ord x + 32) : newList xs 
               else x : newList xs  

or with guards

newList :: String -> String
newList [] = []
newList (x:xs)
    | x `elem` ['A'..'Z'] = chr (ord x + 32) : newList xs 
    | otherwise = x : newList xs 
like image 25
Bargros Avatar answered Sep 27 '22 19:09

Bargros