Skip to content

Latest commit

 

History

History
89 lines (66 loc) · 2.09 KB

README.md

File metadata and controls

89 lines (66 loc) · 2.09 KB

gd3_fp

Minimal, single-file functional programming module for Godot Engine 3.0

Adapted from: https://georgemarques.com.br/functional-gdscript.pdf

Usage

Preload the script to access the static functions

const FP := preload("res://fp.gd")

Map

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

static func add_one(num: int) -> int:
	return num + 1

var input := [1, 2, 3]
var output := FP.map(input, funcref(self, "add_one"))  # [2, 3, 4]

Filter

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

static func is_even(num: int) -> bool:
	return num % 2 == 0

var input := [1, 2, 3, 4]
var output := FP.filter(input, funcref(self, "is_even"))  # [2, 4]

Reduce

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

static func sum(a: int, b: int) -> int:
	return a + b

var input := [1, 2, 3]
var output := FP.reduce(input, funcref(self, "sum"))  # 6

Pipe

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

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