arliss_obsidian/fp/Language/Functions/Currying.md

46 lines
1.1 KiB
Markdown
Raw Normal View History

2024-09-23 23:56:55 +00:00
[[Functions]] are curried in PureScript, meaning that "a function of 2 arguments" is actually "a function of 1 argument, returning a function of 1 argument."
This allows you to call many functions point-free, and think in terms of "building up to a conclusion" rather than "i need everything at once."
e.g.
```haskell
add :: Int -> Int -> Int
-- ...
add2 :: Int -> Int
add2 n = add 2 n
```
is equivalent to
```haskell
add :: Int -> Int -> Int
-- ...
add2 :: Int -> Int
add2 = add 2
```
Walking through this:
`add` has type `Int -> Int -> Int`
if we give `add` a single `Int` argument, it will return a function of type `Int -> Int`. This function is the "second half" of `add`, waiting for it's second argument. Since `Int -> Int` is the type of `add2`, we can simply say `add2 = add 2`.
> [!info]
> as a rule, any time a function's last argument is passed as the last argument to another function, you can remove both.
> ```haskell
> f a = g b c a
>
> \a -> g b c a
>
> f a = g $ h a
> ```
> can be written as
> ```haskell
> f = g b c
>
> g b c
>
> f = g <<< h
> ```