[Haskell-beginners] a simple little problem

Dennis Raddle dennis.raddle at gmail.com
Sat Aug 13 20:04:57 CEST 2011


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)

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]



More information about the Beginners mailing list