Obsidian_42
Obsidian_42

Reputation: 21

How to write a code in Haskell to filter out Nothing values from a list

I wish to "map a list and drop it if the map function returns Nothing". I am doing as follows:-

    filteredList f l = map to_int (mapMaybe f l)

The to_int function here is as follows

    to_int some_value = case some_value of
      Just a -> a
      Nothing -> 0

This although logically correct to me, is not working as it should. Can someone please explain where I am wrong here?

Upvotes: 1

Views: 486

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477065

What you are trying to implement already exists. Indeed, mapMaybe :: (a -> Maybe b) -> [a] -> [b] will take function and a list, call the function on the elements of the list, and retrieve the items that returned a Just … object. The items are unwrapped from the Just data constructor.

This function is defined in the base package, but not in the Prelude. This means that you should import this from the Data.Maybe module:

import Data.Maybe(mapMaybe)

filteredList :: (a -> Maybe b) -> [a] -> [b]
filteredList = mapMaybe

You can specialize this for example with a ~ b ~ Integer and thus use this as (Integer -> Maybe Integer) -> [Integer] -> [Integer].

You can also implement this function yourself, for example with list comprehension:

filteredList :: (a -> Maybe b) -> [a] -> [b]
filteredList f l = [ y | Just y <- map f l ]

Here we thus use pattern matching to ensure that we receive an Just x pattern. If the pattern does not match, then this item is skipped. We also unwrap the y from the Just y pattern, and use this as item to put in the list.

Upvotes: 2

Related Questions