Playground
fp.gno
// Package fp provides functional programming utilities for Gno, enabling
// transformations, filtering, and other operations on slices of any.
//
// Example of chaining operations:
//
// numbers := []any{1, 2, 3, 4, 5, 6}
//
// // Define predicates, mappers and reducers
// isEven := func(v any) bool { return v.(int)%2 == 0 }
// double := func(v any) any { return v.(int) * 2 }
// sum := func(a, b any) any { return a.(int) + b.(int) }
//
// // Chain operations: filter even numbers, double them, then sum
// evenNums := Filter(numbers, isEven) // [2, 4, 6]
// doubled := Map(evenNums, double) // [4, 8, 12]
// result := Reduce(doubled, sum, 0) // 24
//
// // Alternative: group by even/odd, then get even numbers
// byMod2 := func(v any) any { return v.(int) % 2 }
// grouped := GroupBy(numbers, byMod2) // {0: [2,4,6], 1: [1,3,5]}
// evens := grouped[0] // [2,4,6]
package fp
// Mapper is a function type that maps an element to another element.
type Mapper func(any) any
// Predicate is a function type that evaluates a condition on an element.
type Predicate func(any) bool
// Reducer is a function type that reduces two elements to a single value.
type Reducer func(any, any) any
// Filter filters elements from the slice that satisfy the given predicate.
//
// Example:
//
// numbers := []any{-1, 0, 1, 2}
// isPositive := func(v any) bool { return v.(int) > 0 }
// result := Filter(numbers, isPositive) // [1, 2]
func Filter(values []any, fn Predicate) []any {
result := []any{}
for _, v := range values {
if fn(v) {
result = append(result, v)
}
}
return result
}
// Map applies a function to each element in the slice.
//
// Example:
//
// numbers := []any{1, 2, 3}
// toString := func(v any) any { return fmt.Sprintf("%d", v) }
// result := Map(numbers, toString) // ["1", "2", "3"]
func Map(values []any, fn Mapper) []any {
result := make([]any, len(values))
for i, v := range values {
result[i] = fn(v)
}
return result
}
// Reduce reduces a slice to a single value by applying a function.
//
// Example:
//
// numbers := []any{1, 2, 3, 4}
// sum := func(a, b any) any { return a.(int) + b.(int) }
// result := Reduce(numbers, sum, 0) // 10
func Reduce(values []any, fn Reducer, initial any) any {
acc := initial
for _, v := range values {
acc = fn(acc, v)
}
return acc
}
// FlatMap maps each element to a collection and flattens the results.
//
// Example:
//
// words := []any{"hello", "world"}
// split := func(v any) any {
// chars := []any{}
// for _, c := range v.(string) {
// chars = append(chars, string(c))
// }
// return chars
// }
// result := FlatMap(words, split) // ["h","e","l","l","o","w","o","r","l","d"]
func FlatMap(values []any, fn Mapper) []any {
result := []any{}
for _, v := range values {
inner := fn(v).([]any)
result = append(result, inner...)
}
return result
}
// All returns true if all elements satisfy the predicate.
//
// Example:
//
// numbers := []any{2, 4, 6, 8}
// isEven := func(v any) bool { return v.(int)%2 == 0 }
// result := All(numbers, isEven) // true
func All(values []any, fn Predicate) bool {
for _, v := range values {
if !fn(v) {
return false
}
}
return true
}
// Any returns true if at least one element satisfies the predicate.
//
// Example:
//
// numbers := []any{1, 3, 4, 7}
// isEven := func(v any) bool { return v.(int)%2 == 0 }
// result := Any(numbers, isEven) // true (4 is even)
func Any(values []any, fn Predicate) bool {
for _, v := range values {
if fn(v) {
return true
}
}
return false
}
// None returns true if no elements satisfy the predicate.
//
// Example:
//
// numbers := []any{1, 3, 5, 7}
// isEven := func(v any) bool { return v.(int)%2 == 0 }
// result := None(numbers, isEven) // true (no even numbers)
func None(values []any, fn Predicate) bool {
for _, v := range values {
if fn(v) {
return false
}
}
return true
}
// Chunk splits a slice into chunks of the given size.
//
// Example:
//
// numbers := []any{1, 2, 3, 4, 5}
// result := Chunk(numbers, 2) // [[1,2], [3,4], [5]]
func Chunk(values []any, size int) [][]any {
if size <= 0 {
return nil
}
var chunks [][]any
for i := 0; i < len(values); i += size {
end := i + size
if end > len(values) {
end = len(values)
}
chunks = append(chunks, values[i:end])
}
return chunks
}
// Find returns the first element that satisfies the predicate and a boolean indicating if an element was found.
//
// Example:
//
// numbers := []any{1, 2, 3, 4}
// isEven := func(v any) bool { return v.(int)%2 == 0 }
// result, found := Find(numbers, isEven) // 2, true
func Find(values []any, fn Predicate) (any, bool) {
for _, v := range values {
if fn(v) {
return v, true
}
}
return nil, false
}
// Reverse reverses the order of elements in a slice.
//
// Example:
//
// numbers := []any{1, 2, 3}
// result := Reverse(numbers) // [3, 2, 1]
func Reverse(values []any) []any {
result := make([]any, len(values))
for i, v := range values {
result[len(values)-1-i] = v
}
return result
}
// Zip combines two slices into a slice of pairs. If the slices have different lengths,
// extra elements from the longer slice are ignored.
//
// Example:
//
// a := []any{1, 2, 3}
// b := []any{"a", "b", "c"}
// result := Zip(a, b) // [[1,"a"], [2,"b"], [3,"c"]]
func Zip(a, b []any) [][2]any {
length := min(len(a), len(b))
result := make([][2]any, length)
for i := 0; i < length; i++ {
result[i] = [2]any{a[i], b[i]}
}
return result
}
// Unzip splits a slice of pairs into two separate slices.
//
// Example:
//
// pairs := [][2]any{{1,"a"}, {2,"b"}, {3,"c"}}
// numbers, letters := Unzip(pairs) // [1,2,3], ["a","b","c"]
func Unzip(pairs [][2]any) ([]any, []any) {
a := make([]any, len(pairs))
b := make([]any, len(pairs))
for i, pair := range pairs {
a[i] = pair[0]
b[i] = pair[1]
}
return a, b
}
// GroupBy groups elements based on a key returned by a Mapper.
//
// Example:
//
// numbers := []any{1, 2, 3, 4, 5, 6}
// byMod3 := func(v any) any { return v.(int) % 3 }
// result := GroupBy(numbers, byMod3) // {0: [3,6], 1: [1,4], 2: [2,5]}
func GroupBy(values []any, fn Mapper) map[any][]any {
result := make(map[any][]any)
for _, v := range values {
key := fn(v)
result[key] = append(result[key], v)
}
return result
}
// Flatten flattens a slice of slices into a single slice.
//
// Example:
//
// nested := [][]any{{1,2}, {3,4}, {5}}
// result := Flatten(nested) // [1,2,3,4,5]
func Flatten(values [][]any) []any {
result := []any{}
for _, v := range values {
result = append(result, v...)
}
return result
}
// Helper functions
func min(a, b int) int {
if a < b {
return a
}
return b
}
fp_test.gno
package fp
import (
"testing"
"gno.land/p/nt/ufmt/v0"
)
func TestMap(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) any
expected []any
}{
{
name: "multiply numbers by 2",
input: []any{1, 2, 3},
fn: func(v any) any { return v.(int) * 2 },
expected: []any{2, 4, 6},
},
{
name: "empty slice",
input: []any{},
fn: func(v any) any { return v.(int) * 2 },
expected: []any{},
},
{
name: "convert numbers to strings",
input: []any{1, 2, 3},
fn: func(v any) any { return ufmt.Sprintf("%d", v.(int)) },
expected: []any{"1", "2", "3"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Map(tt.input, tt.fn)
if !equalSlices(result, tt.expected) {
t.Errorf("Map failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestFilter(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) bool
expected []any
}{
{
name: "filter even numbers",
input: []any{1, 2, 3, 4},
fn: func(v any) bool { return v.(int)%2 == 0 },
expected: []any{2, 4},
},
{
name: "empty slice",
input: []any{},
fn: func(v any) bool { return v.(int)%2 == 0 },
expected: []any{},
},
{
name: "no matches",
input: []any{1, 3, 5},
fn: func(v any) bool { return v.(int)%2 == 0 },
expected: []any{},
},
{
name: "all matches",
input: []any{2, 4, 6},
fn: func(v any) bool { return v.(int)%2 == 0 },
expected: []any{2, 4, 6},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Filter(tt.input, tt.fn)
if !equalSlices(result, tt.expected) {
t.Errorf("Filter failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestReduce(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any, any) any
initial any
expected any
}{
{
name: "sum numbers",
input: []any{1, 2, 3},
fn: func(a, b any) any { return a.(int) + b.(int) },
initial: 0,
expected: 6,
},
{
name: "empty slice",
input: []any{},
fn: func(a, b any) any { return a.(int) + b.(int) },
initial: 0,
expected: 0,
},
{
name: "concatenate strings",
input: []any{"a", "b", "c"},
fn: func(a, b any) any { return a.(string) + b.(string) },
initial: "",
expected: "abc",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Reduce(tt.input, tt.fn, tt.initial)
if result != tt.expected {
t.Errorf("Reduce failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestFlatMap(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) any
expected []any
}{
{
name: "split words into chars",
input: []any{"go", "fn"},
fn: func(word any) any {
chars := []any{}
for _, c := range word.(string) {
chars = append(chars, string(c))
}
return chars
},
expected: []any{"g", "o", "f", "n"},
},
{
name: "empty string handling",
input: []any{"", "a", ""},
fn: func(word any) any {
chars := []any{}
for _, c := range word.(string) {
chars = append(chars, string(c))
}
return chars
},
expected: []any{"a"},
},
{
name: "nil handling",
input: []any{nil, "a", nil},
fn: func(word any) any {
if word == nil {
return []any{}
}
return []any{word}
},
expected: []any{"a"},
},
{
name: "empty slice result",
input: []any{"", "", ""},
fn: func(word any) any {
return []any{}
},
expected: []any{},
},
{
name: "nested array flattening",
input: []any{1, 2, 3},
fn: func(n any) any {
return []any{n, n}
},
expected: []any{1, 1, 2, 2, 3, 3},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := FlatMap(tt.input, tt.fn)
if !equalSlices(result, tt.expected) {
t.Errorf("FlatMap failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestAllAnyNone(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) bool
expectedAll bool
expectedAny bool
expectedNone bool
}{
{
name: "all even numbers",
input: []any{2, 4, 6, 8},
fn: func(x any) bool { return x.(int)%2 == 0 },
expectedAll: true,
expectedAny: true,
expectedNone: false,
},
{
name: "no even numbers",
input: []any{1, 3, 5, 7},
fn: func(x any) bool { return x.(int)%2 == 0 },
expectedAll: false,
expectedAny: false,
expectedNone: true,
},
{
name: "mixed even/odd numbers",
input: []any{1, 2, 3, 4},
fn: func(x any) bool { return x.(int)%2 == 0 },
expectedAll: false,
expectedAny: true,
expectedNone: false,
},
{
name: "empty slice",
input: []any{},
fn: func(x any) bool { return x.(int)%2 == 0 },
expectedAll: true, // vacuously true
expectedAny: false, // vacuously false
expectedNone: true, // vacuously true
},
{
name: "nil predicate handling",
input: []any{nil, nil, nil},
fn: func(x any) bool { return x == nil },
expectedAll: true,
expectedAny: true,
expectedNone: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resultAll := All(tt.input, tt.fn)
if resultAll != tt.expectedAll {
t.Errorf("All failed, expected %v, got %v", tt.expectedAll, resultAll)
}
resultAny := Any(tt.input, tt.fn)
if resultAny != tt.expectedAny {
t.Errorf("Any failed, expected %v, got %v", tt.expectedAny, resultAny)
}
resultNone := None(tt.input, tt.fn)
if resultNone != tt.expectedNone {
t.Errorf("None failed, expected %v, got %v", tt.expectedNone, resultNone)
}
})
}
}
func TestChunk(t *testing.T) {
tests := []struct {
name string
input []any
size int
expected [][]any
}{
{
name: "normal chunks",
input: []any{1, 2, 3, 4, 5},
size: 2,
expected: [][]any{{1, 2}, {3, 4}, {5}},
},
{
name: "empty slice",
input: []any{},
size: 2,
expected: [][]any{},
},
{
name: "chunk size equals length",
input: []any{1, 2, 3},
size: 3,
expected: [][]any{{1, 2, 3}},
},
{
name: "chunk size larger than length",
input: []any{1, 2},
size: 3,
expected: [][]any{{1, 2}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Chunk(tt.input, tt.size)
if !equalNestedSlices(result, tt.expected) {
t.Errorf("Chunk failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestFind(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) bool
expected any
shouldFound bool
}{
{
name: "find first number greater than 2",
input: []any{1, 2, 3, 4},
fn: func(v any) bool { return v.(int) > 2 },
expected: 3,
shouldFound: true,
},
{
name: "empty slice",
input: []any{},
fn: func(v any) bool { return v.(int) > 2 },
expected: nil,
shouldFound: false,
},
{
name: "no match",
input: []any{1, 2},
fn: func(v any) bool { return v.(int) > 10 },
expected: nil,
shouldFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := Find(tt.input, tt.fn)
if found != tt.shouldFound {
t.Errorf("Find failed, expected found=%v, got found=%v", tt.shouldFound, found)
}
if found && result != tt.expected {
t.Errorf("Find failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestReverse(t *testing.T) {
tests := []struct {
name string
input []any
expected []any
}{
{
name: "normal sequence",
input: []any{1, 2, 3, 4},
expected: []any{4, 3, 2, 1},
},
{
name: "empty slice",
input: []any{},
expected: []any{},
},
{
name: "single element",
input: []any{1},
expected: []any{1},
},
{
name: "mixed types",
input: []any{1, "a", true, 2.5},
expected: []any{2.5, true, "a", 1},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Reverse(tt.input)
if !equalSlices(result, tt.expected) {
t.Errorf("Reverse failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestZipUnzip(t *testing.T) {
tests := []struct {
name string
a []any
b []any
expectedZip [][2]any
expectedA []any
expectedB []any
}{
{
name: "normal case",
a: []any{1, 2, 3},
b: []any{"a", "b", "c"},
expectedZip: [][2]any{{1, "a"}, {2, "b"}, {3, "c"}},
expectedA: []any{1, 2, 3},
expectedB: []any{"a", "b", "c"},
},
{
name: "empty slices",
a: []any{},
b: []any{},
expectedZip: [][2]any{},
expectedA: []any{},
expectedB: []any{},
},
{
name: "different lengths - a shorter",
a: []any{1, 2},
b: []any{"a", "b", "c"},
expectedZip: [][2]any{{1, "a"}, {2, "b"}},
expectedA: []any{1, 2},
expectedB: []any{"a", "b"},
},
{
name: "different lengths - b shorter",
a: []any{1, 2, 3},
b: []any{"a"},
expectedZip: [][2]any{{1, "a"}},
expectedA: []any{1},
expectedB: []any{"a"},
},
{
name: "mixed types",
a: []any{1, true, "x"},
b: []any{2.5, false, "y"},
expectedZip: [][2]any{{1, 2.5}, {true, false}, {"x", "y"}},
expectedA: []any{1, true, "x"},
expectedB: []any{2.5, false, "y"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
zipped := Zip(tt.a, tt.b)
if len(zipped) != len(tt.expectedZip) {
t.Errorf("Zip failed, expected length %v, got %v", len(tt.expectedZip), len(zipped))
}
for i, pair := range zipped {
if pair[0] != tt.expectedZip[i][0] || pair[1] != tt.expectedZip[i][1] {
t.Errorf("Zip failed at index %d, expected %v, got %v", i, tt.expectedZip[i], pair)
}
}
unzippedA, unzippedB := Unzip(zipped)
if !equalSlices(unzippedA, tt.expectedA) {
t.Errorf("Unzip failed for slice A, expected %v, got %v", tt.expectedA, unzippedA)
}
if !equalSlices(unzippedB, tt.expectedB) {
t.Errorf("Unzip failed for slice B, expected %v, got %v", tt.expectedB, unzippedB)
}
})
}
}
func TestGroupBy(t *testing.T) {
tests := []struct {
name string
input []any
fn func(any) any
expected map[any][]any
}{
{
name: "group by even/odd",
input: []any{1, 2, 3, 4, 5, 6},
fn: func(v any) any { return v.(int) % 2 },
expected: map[any][]any{
0: {2, 4, 6},
1: {1, 3, 5},
},
},
{
name: "empty slice",
input: []any{},
fn: func(v any) any { return v.(int) % 2 },
expected: map[any][]any{},
},
{
name: "single group",
input: []any{2, 4, 6},
fn: func(v any) any { return v.(int) % 2 },
expected: map[any][]any{
0: {2, 4, 6},
},
},
{
name: "group by type",
input: []any{1, "a", 2, "b", true},
fn: func(v any) any {
switch v.(type) {
case int:
return "int"
case string:
return "string"
default:
return "other"
}
},
expected: map[any][]any{
"int": {1, 2},
"string": {"a", "b"},
"other": {true},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := GroupBy(tt.input, tt.fn)
if len(result) != len(tt.expected) {
t.Errorf("GroupBy failed, expected %d groups, got %d", len(tt.expected), len(result))
}
for k, v := range tt.expected {
if !equalSlices(result[k], v) {
t.Errorf("GroupBy failed for key %v, expected %v, got %v", k, v, result[k])
}
}
})
}
}
func TestFlatten(t *testing.T) {
tests := []struct {
name string
input [][]any
expected []any
}{
{
name: "normal nested slices",
input: [][]any{{1, 2}, {3, 4}, {5}},
expected: []any{1, 2, 3, 4, 5},
},
{
name: "empty outer slice",
input: [][]any{},
expected: []any{},
},
{
name: "empty inner slices",
input: [][]any{{}, {}, {}},
expected: []any{},
},
{
name: "mixed types",
input: [][]any{{1, "a"}, {true, 2.5}, {nil}},
expected: []any{1, "a", true, 2.5, nil},
},
{
name: "single element slices",
input: [][]any{{1}, {2}, {3}},
expected: []any{1, 2, 3},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Flatten(tt.input)
if !equalSlices(result, tt.expected) {
t.Errorf("Flatten failed, expected %v, got %v", tt.expected, result)
}
})
}
}
func TestContains(t *testing.T) {
tests := []struct {
name string
slice []any
item any
expected bool
}{
{
name: "contains integer",
slice: []any{1, 2, 3},
item: 2,
expected: true,
},
{
name: "does not contain integer",
slice: []any{1, 2, 3},
item: 4,
expected: false,
},
{
name: "contains string",
slice: []any{"a", "b", "c"},
item: "b",
expected: true,
},
{
name: "empty slice",
slice: []any{},
item: 1,
expected: false,
},
{
name: "contains nil",
slice: []any{1, nil, 3},
item: nil,
expected: true,
},
{
name: "mixed types",
slice: []any{1, "a", true},
item: true,
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := contains(tt.slice, tt.item)
if result != tt.expected {
t.Errorf("contains failed, expected %v, got %v", tt.expected, result)
}
})
}
}
// Helper function for testing
func contains(slice []any, item any) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}
// Helper functions for comparing slices
func equalSlices(a, b []any) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func equalNestedSlices(a, b [][]any) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !equalSlices(a[i], b[i]) {
return false
}
}
return true
}
gnomod.toml
module = "gno.land/p/nym-moultest123/fp/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186404 max_deposit = "10000000ugnot"