[Haskell-beginners] a simple little problem
Daniel Fischer
daniel.is.fischer at googlemail.com
Sat Aug 13 20:45:57 CEST 2011
On Saturday 13 August 2011, 20:04:57, Dennis Raddle wrote:
> Can someone suggest an elegant way to write the following?
>
> fn :: [Maybe Float] -> Maybe Float
>
> in which, if the input list has all Nothing, then the result is Nothing
> if the input list has one or more Just x, then the result is Just x
> (in which the x is picked arbitrarily, could be the first one or last
> one)
import Control.Monad
fn = msum
(or, with only imports from Data.Maybe: listToMaybe . catMaybes)
>
> I have something like
>
> import Data.Maybe
> fn list = case catMaybes list of
> [] -> Nothing
> [x:_] -> fromJust x
>
> Next, an augmentation of this idea (or similar idea).
>
> fn2 :: [Maybe Float] -> Map Int Float
>
> When a Just x appears at position n in the list, then put (key=n,
> value=x) into the map.
>
> I have:
>
> import qualified Data.Map as M
> f2 list = M.fromList [(n,x) | (n,Just x) <- zip [0..] list]
>
That's fine.
More information about the Beginners
mailing list