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

Stephen Tetley stephen.tetley at gmail.com
Thu Apr 29 13:40:56 EDT 2010


On 29 April 2010 15:48, matthew coolbeth <mac01021 at engr.uconn.edu> wrote:
> I understand that higher-order functions  are incredibly powerful, and that
> you can do essentially anything you might ever want while using only 'map'
> and 'foldl'.

Hello

In this case neither map nor foldl are adequate as both provide an
'elementary' consumption pattern i.e. one item is consumed at each
step.

mapAccumL can be seeded with a state tracking the previous element,
though as others have said you might want to define your own recursion
scheme:

replace2 :: (a -> a -> a) -> a -> [a] -> [a]
replace2 f2 initial xs = snd $ mapAccumL fn initial xs
  where
    fn a x = (x, f2 a x)

-- some example
replaceCharAfterA :: String -> String
replaceCharAfterA = replace2 fn 'Z'     -- seed 'state' with 'Z' (wont match)
  where
    fn 'A' _ = '*'
    fn _   b = b

demo1 = replaceCharAfterA "abcABC"

> demo1
"abcA*C"

Best wishes

Stephen


More information about the Beginners mailing list