[Haskell-cafe] New to Haskell - List Comprehension Question

michael rice nowgate at yahoo.com
Wed Oct 7 18:09:09 EDT 2009


Try just writing a function that will change ALL the characters to uppercase (or lower case) using list comprehension and then see if you can isolate how to factor out the special case of the first character.

Michael

--- On Wed, 10/7/09, minh thu <noteed at gmail.com> wrote:

From: minh thu <noteed at gmail.com>
Subject: Re: [Haskell-cafe] New to Haskell - List Comprehension Question
To: "Steven1990" <stevenyoung1990 at msn.com>
Cc: haskell-cafe at haskell.org
Date: Wednesday, October 7, 2009, 5:20 PM

2009/10/7 Steven1990 <stevenyoung1990 at msn.com>:
>
> Hi, I'm currently learning Haskell, and I've been trying to work out a
> function for the following problem for a couple of days now.
>
> I want to use a list comprehension method to change the first letter of a
> string to upper case, and the rest of the string to lower case.
>
> Eg: "heLLo" -> "Hello"
>
> As I'm trying to learn this, I would appreciate hints rather than the
> explicit solution if possible? I'm sure I'm close to a solution, I must be
> missing something though. Driving me crazy!
>
> My attempts are something similar to this:
>
> upperCase :: String -> String
> upperCase xs = [toUpper(x):toLower(xs) | x <- xs]
>
> I think 'toLower' expects a single character rather than the list which is
> one place I'm going wrong?

Hi,

try to work little things by little things:

$ ghci
Prelude> let f xs = [x:xs | x <- xs]
Prelude> f "hello"
["hhello","ehello","lhello","lhello","ohello"]
Prelude>

Prelude> :m + Data.Char
Prelude Data.Char> :t toLower
toLower :: Char -> Char
Prelude Data.Char> :t toUpper
toUpper :: Char -> Char
Prelude Data.Char>

So xs is the whole list (the "hello" part of each element in the
resilt of f "hello") and x gets the value of each character. toLower
and toUpper have the same type; indeed toLower expects a single
character while you feed it a list.

The part on the left of the pipe is "executed" for each x drawn from
the xs list. This means that if you want to make something specific to
the first element of xs, you have to provide more information: the x
alone is not enough to know it is the first one or not.

The easiest way to do that is with pattern matching on the upperCase argument:
upperCase (x:xs) = ...

(Don't forget for the "other" case, the empty list:
upperCase [] = ...)

Cheers,
Thu
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091007/e93ba154/attachment.html


More information about the Haskell-Cafe mailing list