https://github.com/menacingmecha/gd3_fp
Minimal, single-file functional programming module for Godot Engine 3.x
https://github.com/menacingmecha/gd3_fp
functional-programming gdscript godot godot-engine
Last synced: 7 months ago
JSON representation
Minimal, single-file functional programming module for Godot Engine 3.x
- Host: GitHub
- URL: https://github.com/menacingmecha/gd3_fp
- Owner: MenacingMecha
- License: mit
- Created: 2022-05-19T01:14:37.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-05-31T17:00:24.000Z (over 3 years ago)
- Last Synced: 2025-02-28T17:46:57.607Z (7 months ago)
- Topics: functional-programming, gdscript, godot, godot-engine
- Language: GDScript
- Homepage:
- Size: 5.86 KB
- Stars: 5
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gd3_fp
Minimal, single-file functional programming module for Godot Engine 3.0Adapted from: https://georgemarques.com.br/functional-gdscript.pdf
## Usage
Preload the script to access the static functions```gdscript
const FP := preload("res://fp.gd")
```## Map
```gdscript
static func map(input: Array, function: FuncRef) -> Array:
```
Calls `function` on each element of `input`, returning the transformed outputs from `function`.`function` is required to have a non-void output.
### Example
```gdscript
static func add_one(num: int) -> int:
return num + 1var input := [1, 2, 3]
var output := FP.map(input, funcref(self, "add_one")) # [2, 3, 4]
```## Filter
```gdscript
static func filter(input: Array, function: FuncRef) -> Array:
```Calls `function` on each element of `input`, returning all the elements which returned `true`.
`function` should return a `bool`, but this is not required.
### Example
```gdscript
static func is_even(num: int) -> bool:
return num % 2 == 0var input := [1, 2, 3, 4]
var output := FP.filter(input, funcref(self, "is_even")) # [2, 4]
```## Reduce
```gdscript
static func reduce(input: Array, function: FuncRef, base = null):
```Returns a single output value by calling `function` on each element of the array along with the accumalated result of each iteration.
`function` should take in two inputs.
`base` can optionally be used to define a starting value.
### Example
```gdscript
static func sum(a: int, b: int) -> int:
return a + bvar input := [1, 2, 3]
var output := FP.reduce(input, funcref(self, "sum")) # 6
```## Pipe
```gdscript
static func pipe(input: Array, pipe_pairs: Array):
```Transforms `input` in order through each `Funcref` pair in `pipe_pairs`.
`pipe_pairs` is expected to be an array of arrays, with a higher-order function `Funcref` followed by an appropriate transformative function `Funcref`.
### Example
```gdscript
var input := [1, 2, 3, 4]
var output = FP.pipe(
input,
[
[funcref(FP, "filter"), funcref(self, "is_even")],
[funcref(FP, "map"), funcref(self, "add_one")],
[funcref(FP, "reduce"), funcref(self, "sum")]
]
) # 8
```