forked from orion/obsidian
52 lines
1005 B
Markdown
52 lines
1005 B
Markdown
|
Alt is used most often as boolean OR on fallible [[Functor|functors]], but is technically whatever associative operation makes sense for the [[Data Structures|data]] type.
|
||
|
|
||
|
```haskell
|
||
|
class Functor f <= Alt f where
|
||
|
alt :: forall a. f a -> f a -> f a
|
||
|
```
|
||
|
|
||
|
### Examples
|
||
|
In [[Maybe]], Alt allows chainable defaults:
|
||
|
```haskell
|
||
|
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:
|
||
|
```haskell
|
||
|
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:
|
||
|
```haskell
|
||
|
[] <|> [] -- []
|
||
|
|
||
|
["a"] <|> [] -- ["a"]
|
||
|
|
||
|
[] <|> ["a"] -- ["a"]
|
||
|
|
||
|
["a"] <|> ["b"] -- ["a", "b"]
|
||
|
["a"] <|> ["b", "c"] -- ["a", "b", "c"]
|
||
|
```
|