Skip to content

Instantly share code, notes, and snippets.

@afcondon
Last active July 8, 2020 10:56
Show Gist options
  • Save afcondon/a22c2b80c60c16882c2a889b14afb054 to your computer and use it in GitHub Desktop.
Save afcondon/a22c2b80c60c16882c2a889b14afb054 to your computer and use it in GitHub Desktop.
Nested Maybes
module Main where
import Prelude (Unit, pure, bind, ($), show, class Show)
import Effect (Effect)
import Data.Maybe (Maybe(Just, Nothing))
import Data.Array (head)
import TryPureScript (p, text, render)
import Data.Foldable (fold)
-- Data.Array provides `head` function which has to return a Maybe because the array could be empty
main :: Effect Unit
main = render $ fold
[ p $ text $ showMaybe $ unpackNested nested
, p $ text $ showMaybe $ unpackNested nested'
]
showMaybe :: forall a. (Show a) => Maybe a -> String
showMaybe (Just a) = show a
showMaybe Nothing = "Nothing"
nested :: Array (Array (Array Int))
nested = [[[1,2,3]]]
nested' :: Array (Array (Array Int))
nested' = [[[]]]
unpackNested :: forall a. Array (Array (Array a)) -> Maybe a
unpackNested nest = do
first <- head nest
second <- head first
third <- head second
pure third
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment