[Haskell-beginners] Re: Iterating through a list of char...

Dupont Corentin corentin.dupont at gmail.com
Wed Apr 28 11:40:04 EDT 2010


Hello,

I would do:

doSmthg a = if a == 'a' then (const 'A') else id

trans c = zipWith doSmthg (" " ++ c) c

> trans "arga"
"aAga"

The idea is to zip the string with the same string with an offset of character.
I thing my solution could be cleaner by using Maybe monad to handle
the first character's problem.

Corentin



On 4/28/10, Maciej Piechotka <uzytkownik2 at gmail.com> wrote:
> On Wed, 2010-04-28 at 10:56 -0400, Jean-Nicolas Jolivet wrote:
>> Hi there!
>>
>> I'm trying to iterate through each character of a string (that part I
>> can do!) however, I need to apply a transformation to each
>> character...based on the previous character in the string! This is the
>> part I have no clue how to do!
>>
>> I'm totally new to Haskell so I'm pretty sure I'm missing something
>> obvious... I tried with list comprehensions...map... etc... but I
>> can't figure out how I can access the previous character in my string
>> in each "iteration".... to use simple pseudo code, what i need to do
>> is:
>>
>> while i < my_string length:
>
> I assume i > 0 as otherwise my_string[i-1] is illegal
>
>> 	if my_string[i-1] == some_char:
>> 		do something with my_string[i]
>> 	else
>> 		do something else with my_string[i]
>>
>> I'm using imperative programming here obviously since it's what I am
>> familiar with...but any help as to how I could "translate" this to
>> functional programming would be really appreciated!
>>
>>
>> Jean-Nicolas Jolivet
>
> Very simple version:
>
> func (x:xs) = x:helper x xs
> func []     = []
>
> helper p (x:xs) | p == some_char = x':helper x' xs
>                 | otherwise      = x'':helper x'' xs
>                 where x' = doSomething x
>                       x'' = doSomethingElse x
> helper p []                      = []
>
> or (for helper):
>
> helper p (x:xs) = let x' | p == some_char = doSomething x
>                          | otherwise      = doSomethingElse x
>                   in x':helper x' xs
> helper p []     = []
>
> Advanced version (depends on state of character before change)
>
> func s@(x:xs) = x:zipWith proc s xs
>                 where proc (p, x) | p == some_char = doSomething x
>                                   | otherwise      = soSomethingElse x
>
> Advanced version:
>
> func (x:xs) = let s = x:zipWith proc s xs
>                   proc (p, x) | p == some_char = doSomething x
>                               | otherwise      = soSomethingElse x
>               in s
>
> It can be also expressed using folds. Choose version which suits you
> best.
>
> Regards
>


More information about the Beginners mailing list