arliss_obsidian/fp/Classes/Alternative/Alt.md
Orion Kindel d74fc46755
update
2024-09-24 14:53:59 -05:00

1005 B

Alt is used most often as boolean OR on fallible Functor, but is technically whatever associative operation makes sense for the Data Structures type.

class Functor f <= Alt f where
  alt :: forall a. f a -> f a -> f a

Examples

In Maybe, Alt allows chainable defaults:

Just 1 <|> Just 2
-- Just 1

Nothing <|> Just 1
-- Just 1

Nothing <|> Nothing
-- Nothing

Nothing <|> Nothing <|> Just 1
-- Just 1

In Either, Alt works as a try/catch:

Left "error!" <|> Right "it's ok i recovered"
-- Right "it's ok i recovered"

Right "i succeeded!" <|> Right "backup"
-- Right "i succeeded!"

Right unit <|> Left "uh oh!"
-- Right unit

Left "a" <|> Left "b"
-- Left "b"

[!attention] Note that Alt in Either takes the last Left when all are Left!

In Array, Alt is append:

[] <|> []    -- []

["a"] <|> [] -- ["a"]

[] <|> ["a"] -- ["a"]

["a"] <|> ["b"] -- ["a", "b"]
["a"] <|> ["b", "c"] -- ["a", "b", "c"]