Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Created April 24, 2024 14:39
Show Gist options
  • Save turboMaCk/8eac165bddd4dd11e85aa8a243759753 to your computer and use it in GitHub Desktop.
Save turboMaCk/8eac165bddd4dd11e85aa8a243759753 to your computer and use it in GitHub Desktop.
Tail recursion example
{-# LANGUAGE LambdaCase #-}
module Partition (main) where
-- original implementation
partitionMaybe' :: (a -> Maybe b) -> [a] -> ([(a, b)], [a])
partitionMaybe' f = go
where
go = \case
[] -> ([], [])
(head : tail) ->
let (withs, withouts) = go tail
in case f head of
Nothing -> (withs, head : withouts)
Just b -> ((head, b) : withs, withouts)
-- tail recursive variant
partitionMaybe :: (a -> Maybe b) -> [a] -> ([(a, b)], [a])
partitionMaybe f = go ([], [])
where
go (withs, withouts) = \case
[] -> (reverse withs, reverse withouts)
(head : tail) ->
case f head of
Nothing -> go (withs, head : withouts) tail
Just b -> go ((head, b) : withs, withouts) tail
main = do
let res1 = partitionMaybe' f xs
let res2 = partitionMaybe f xs
putStrLn $ show $ res1 == res2
putStrLn "--"
putStrLn $ show $ res1
putStrLn "--"
putStrLn $ show $ res2
where
xs = [1..100]
f a =
if a `mod` 2 == 0
then Just "huray!"
else Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment