>>> catMaybes [Just 1, Nothing, Just 3] [1,3]When constructing a list of Maybe values, catMaybes can be used to return all of the "success" results (if the list is the result of a map, then mapMaybe would be more appropriate):
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [Just 1,Nothing,Just 3] >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [1,3]
>>> catMaybes [Just 1, Nothing, Just 3] [1,3]When constructing a list of Maybe values, catMaybes can be used to return all of the "success" results (if the list is the result of a map, then mapMaybe would be more appropriate):
>>> import Text.Read ( readMaybe ) >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [Just 1,Nothing,Just 3] >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [1,3]
>>> sequenceA [Just 1, Just 2, Just 3] Just [1,2,3]
>>> sequenceA [Right 1, Right 2, Right 3] Right [1,2,3]The next two example show Nothing and Just will short circuit the resulting structure if present in the input. For more context, check the Traversable instances for Either and Maybe.
>>> sequenceA [Just 1, Just 2, Just 3, Nothing] Nothing
>>> sequenceA [Right 1, Right 2, Right 3, Left 4] Left 4
>>> sequence $ Right [1,2,3,4] [Right 1,Right 2,Right 3,Right 4]
>>> sequence $ [Right 1,Right 2,Right 3,Right 4] Right [1,2,3,4]The following examples demonstrate short circuit behavior for sequence.
>>> sequence $ Left [1,2,3,4] Left [1,2,3,4]
>>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4] Left 0