Latest non-Nothing values in a list

Viewed 145

I have recently started learning Haskell and I hope you can help with a list transformation question.

I have a Maybe list of a custom data type, simplified to Strings for this forum, and I want transform it to replace Nothing values with the most recently seen value. See below:

Input: [Nothing, Just "Hello", Nothing, Nothing, Just "World", Nothing]
Output: [Nothing, Just "Hello", Just "Hello", Just "Hello", Just "World", Just "World"]

Is this possible in Haskell? Any pointers will be much appreciated.

1 Answers

Here's a very concise and elegant way of implementing this:

import Control.Applicative

f = scanl1 (flip (<|>))

Doing f [w,x,y,z] yields [w, x <|> w, y <|> x <|> w, z <|> y <|> x <|> w], and chaining Maybes with <|> gives you the first one that's Just, or Nothing if they're all Nothing.

Related