Last active
November 4, 2021 18:09
-
-
Save thomasdarimont/c4704a45c9ccce0f6792a805719e9a62 to your computer and use it in GitHub Desktop.
Code golf for function composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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