v0 source pure
Package fp provides functional programming utilities for Gno, enabling transformations, filtering, and other operatio...
View source
gno.land/p/moul/fp
Functional helpers over []any: the map / filter / reduce set, plus the
grouping and zipping pieces that usually get rewritten inline.
1numbers := []any{1, 2, 3, 4, 5, 6}
2
3isEven := func(v any) bool { return v.(int)%2 == 0 }
4double := func(v any) any { return v.(int) * 2 }
5sum := func(a, b any) any { return a.(int) + b.(int) }
6
7evens := fp.Filter(numbers, isEven) // [2 4 6]
8bigger := fp.Map(evens, double) // [4 8 12]
9total := fp.Reduce(bigger, sum, 0) // 24
The set
| transform | Map, FlatMap, Filter, Reduce |
| test | All, Any, None, Find |
| reshape | Chunk, Reverse, Flatten, Zip, Unzip, GroupBy |
Three named function types keep signatures readable: Mapper func(any) any,
Predicate func(any) bool, Reducer func(any, any) any.
Two things to know before using it
- Everything is
[]any. Gno has no generics, so element access means a type assertion in your own callback, and a wrong one panics at runtime instead of failing to compile. Keep slices homogeneous. - Every call allocates a new slice. Chaining four operations over a large collection allocates four times. That is fine for rendering a page and wrong for a hot path over persisted state, where a single explicit loop is both cheaper and clearer.
GroupBy returns map[any][]any, so the key must be a comparable type.
Part of moul/gno-contracts — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.
⚠️ Disclaimer: provided as-is, without warranty; not security-audited. Full disclaimer: DISCLAIMER.
Package fp provides functional programming utilities for Gno, enabling transformations, filtering, and other operations on slices of any.
Example of chaining operations:
Example
1numbers := []any{1, 2, 3, 4, 5, 6}
2
3// Define predicates, mappers and reducers
4isEven := func(v any) bool { return v.(int)%2 == 0 }
5double := func(v any) any { return v.(int) * 2 }
6sum := func(a, b any) any { return a.(int) + b.(int) }
7
8// Chain operations: filter even numbers, double them, then sum
9evenNums := Filter(numbers, isEven) // [2, 4, 6]
10doubled := Map(evenNums, double) // [4, 8, 12]
11result := Reduce(doubled, sum, 0) // 24
12
13// Alternative: group by even/odd, then get even numbers
14byMod2 := func(v any) any { return v.(int) % 2 }
15grouped := GroupBy(numbers, byMod2) // {0: [2,4,6], 1: [1,3,5]}
16evens := grouped[0] // [2,4,6]
14
3
Imports 0
Imports nothing.