Search code examples
haskellfunctorpurescript

Whats the right way to handle (deeply nested) functors?


I have the following simple code

import Data.String.Regex
import Data.Array

last <$> match someRegex "   1"

where

match someRegex "   1"

returns something like

Just ([Just ("   1"),Just ("   "),Just ("1")])

and

last <$> match someRegex "   1"

returns something like

Just (Just (Just ("   1"))) 

Now I have a deeply nested Maybe. Which makes it sort of hard to work with (even using functors). I have written myself a pair of helper functions - but I am sort of unhappy with that. It somehow doesn't feel right.

extract j = do
    case j of
        Nothing -> Nothing
        Just a -> a
extract2 jj = extract $ extract jj

And then using it like this

extract2 $ last <$> match someRegex "   1"

Is there a better/idiomatic way to do such things in Purescript/Haskell?


Solution

  • Perhaps you're looking for the join function:

    http://pursuit.purescript.org/packages/purescript-control/0.3.0/docs/Control.Bind#d:join

    join collapses two layers of a structure down to a single layer, combining any effects. In the case of Maybe, that means that the resulting value will not be Nothing only if both layers were not Nothing.