Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
local addOne = (x) -> x + 1
local double = (x) -> x * 2

res1 = double.compose(addOne).apply(5)

local toUpper = (s: String) -> s.toUpperCase()
local exclaim = (s: String) -> "\(s)!"

res2 = exclaim.compose(toUpper).apply("hello")

local addTwo = (x) -> x + 2
local triple = (x) -> x * 3

res3 = triple.compose(addTwo).compose(double).apply(5)

local identity = (x) -> x

res4 = addOne.compose(identity).apply(10)
res5 = identity.compose(addOne).apply(10)

res6 = double.andThen(addOne).apply(5)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
res1 = 12
res2 = "HELLO!"
res3 = 36
res4 = 11
res5 = 11
res6 = 11
19 changes: 19 additions & 0 deletions stdlib/base.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -2205,6 +2205,25 @@ external class Function0<out Result> extends Function<Result> {
external class Function1<in Param1, out Result> extends Function<Result> {
@AlsoKnownAs { names { "call"; "invoke" } }
external function apply(p1: Param1): Result

/// Composes this function with [other].
/// Returns a new function that first applies [other], then applies this function to the result.
///
/// Example:
/// ```
/// local addOne = (x) -> x + 1
/// local double = (x) -> x * 2
/// res = double.compose(addOne).apply(5) // Returns 12
/// ```
@Since { version = "0.31.0" }
function compose<T>(other: Function1<T, Param1>): Function1<T, Result> = (arg) ->
this.apply(other.apply(arg))

/// Composes [other] function with this.
/// Same as `compose` but the functions are executed in reverse order.
@Since { version = "0.31.0" }
function andThen<T>(other: Function1<T, Param1>): Function1<T, Result> = (arg) ->
other.apply(this.apply(arg))
}

/// A function literal with two parameters.
Expand Down