Skip to content

Instantly share code, notes, and snippets.

@KEIII
Created August 3, 2021 20:09
Show Gist options
  • Save KEIII/13732ac213d4549c5f0afcd5e141bbe8 to your computer and use it in GitHub Desktop.
Save KEIII/13732ac213d4549c5f0afcd5e141bbe8 to your computer and use it in GitHub Desktop.
// const :: a -> b -> a
const Const = a => _ => a
// Just :: a -> Maybe a
const Just = a => ({ _tag: 'Just', a });
// Nothing :: Maybe a
const Nothing = { _tag: 'Nothing' };
// (.) :: (b -> c) -> (a -> b) -> a -> c
const compose = bc => ab => a => bc(ab(a));
// foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
const foldr = abb => b => ta => ta.reduceRight((b, a) => abb(a)(b), b);
// listToMaybe :: [a] -> Maybe a
// listToMaybe = foldr (const . Just) Nothing
const listToMaybe = foldr(compose(Const)(Just))(Nothing);
console.log( listToMaybe(['first', 'second', 'third']) ); // { _tag: 'Just', a: 2 }
console.log( listToMaybe([]) ); // { _tag: 'Nothing' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment