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

Maciej Piechotka uzytkownik2 at gmail.com
Wed Apr 28 11:16:25 EDT 2010


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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/beginners/attachments/20100428/17c022a2/attachment.bin


More information about the Beginners mailing list