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

Jean-Nicolas Jolivet jeannicolascocoa at gmail.com
Wed Apr 28 11:39:52 EDT 2010


Thanks a lot! I love the fact that you included different versions! Will definitely look into each versions and try to understand them all!

Jean-Nicolas


On 2010-04-28, at 11:16 AM, Maciej Piechotka 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
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners



More information about the Beginners mailing list