Created
April 24, 2024 14:39
-
-
Save turboMaCk/8eac165bddd4dd11e85aa8a243759753 to your computer and use it in GitHub Desktop.
Tail recursion example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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