[Haskell-beginners] Re: Iterating through a list of char...
Jean-Nicolas Jolivet
jeannicolascocoa at gmail.com
Thu Apr 29 15:37:15 EDT 2010
First I would like to thank everyone for the very interesting replies and suggestions I got so far!...
I tried to implement (and at the very least understand) most of them!...
To add to the context here, what I am trying to do is:
-apply a "transformation" to a character (in my case, subtracting 42 to its ASCII value, which I obtain with chr(ord(c) - 42)
-if the character is preceded by a specific character (that would be, an escape character, in this case '=') then subtract 106 to its value instead of 42...
-if the character is the escape character itself, '=', then skip it altogether (keeping in mind that the next character needs to be escaped)...
I managed to do it, however I'm not totally satisfied in the way I did it... the problem was that... as I just explained, in some cases, the character that is being processed has to be "skipped" (and by that I mean, not added to the resulting string). This happens when the processed character IS the escape character...
What I did was to build a List of Maybe Char.... my function does the proper operation on the character and returns a "Just Char" when the character is processed, or Nothing when it is the escaped character... so basically I would end up with something like: [Just 'f', Just 'o', Just 'o', Nothing]... I am mapping this using mapMaybe to end up with a proper String...
Would there be any more efficient way of doing this? Considering that the escape character should NOT be added to the resulting string, is there any way I can avoid using the Maybe monad?
Once again, thanks everyone for all the suggestions!
Jean-Nicolas Jolivet
On 2010-04-28, at 10:56 AM, 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:
> 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
More information about the Beginners
mailing list