Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active November 4, 2021 18:09
Show Gist options
  • Save thomasdarimont/c4704a45c9ccce0f6792a805719e9a62 to your computer and use it in GitHub Desktop.
Save thomasdarimont/c4704a45c9ccce0f6792a805719e9a62 to your computer and use it in GitHub Desktop.
Code golf for function composition
package main
import (
"fmt"
)
type fn func(int) int
func combine(fns ...fn) fn {
return func(x int) int {
res := x
for _, f := range fns {
res = f(res)
}
return res
}
}
func main() {
addThree := func(x int) int { return x + 3 }
multiplyByTwo := func(x int) int { return x * 2 }
combined := combine(addThree, addThree, multiplyByTwo, multiplyByTwo)
fmt.Println(combined(12))
}
interface fn extends Function<Double,Double>{}
fn addThree = x -> x+3;
fn multiplyByTwo = x -> x*2;
interface fns extends Function<Stream<fn>,Optional<fn>>{}
fns combine = fncs -> fncs.reduce((f,g)-> x -> g.apply(f.apply(x)));
var fun = combine.apply(Stream.of(addThree,addThree,multiplyByTwo,multiplyByTwo)).get();
fun.apply(12.0);
let addThree = x => x+3
let multiplyByTwo = x => x*2
let combine = funcs => funcs.reduce((f,g) => x => g(f(x)))
let fun = combine([addThree,addThree,multiplyByTwo,multiplyByTwo])
fun(12)
from typing import Callable
def addThree(x: float) -> float:
return x + 3
def multiplyByTwo(x: float) -> float:
return x * 2
ComposableFunction = Callable[[float], float]
def compose(*functions: ComposableFunction) -> ComposableFunction:
return functools.reduce(lambda f,g: lambda x: g(f(x)), functions)
def funcDemo():
x = 12
myfunc = compose(addThree, addThree, multiplyByTwo, multiplyByTwo)
result = myfunc(12)
print(f"Result: {result}")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
funcDemo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment