Skip to content

Minimal, single-file functional programming module for Godot Engine 3.x

License

Notifications You must be signed in to change notification settings

MenacingMecha/gd3_fp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Minimal, single-file functional programming module for Godot Engine 3.x

Topics

Resources

License

Stars

Watchers

Forks