The task package provides an abstraction for handling computations that might fail. It builds on the functional programming principles using lazy evaluations and error handling, offering an expressive way to compose functions and manage asynchronous tasks in Go.
To install, run:
go get github.com/venil7/funcThe task library is based on a Task type, which represents a computation that can succeed or fail. By composing functions, users can handle both synchronous and asynchronous computations, and build complex workflows while preserving error handling.
- Task[A any]: The core type, representing a lazy computation that either returns a result of type
Aor an error.
-
Of: Wraps a value in a
Task.func Of[A any](a A) Task[A]
-
Fail: Creates a
Taskthat fails with the given error.func Fail[A any](err error) Task[A]
-
From: Converts a
LazyErrfunction to aTask.func From[A any](f function.LazyErr[A]) Task[A]
-
From1: Converts a single-argument
MapLazyErrfunction to a function returning aTask.func From1[A, B any](f function.MapLazyErr[A, B]) function.Mapping[A, Task[B]]
-
From2: Converts a two-argument function to one that returns a
Task.func From2[A, B, C any](f func(a A, b B) (C, error)) func(a A, b B) Task[C]
-
Map: Applies a mapping function to a
Task's result, returning a newTask.func Map[A any, B any](t Task[A], f function.Mapping[A, B]) Task[B]
-
FlatMap: Chains
Tasks by applying a mapping function that itself returns aTask.func FlatMap[A any, B any](t Task[A], f function.Mapping[A, Task[B]]) Task[B]
-
Tap: Executes a
Taskfor its side effects, discarding the result but preserving the originalTask.func Tap[A, B any](t Task[A], f function.Mapping[A, Task[B]]) Task[A]
-
Then: Combines a
Taskwith aMapLazyErrfunction, creating a sequence of dependent tasks.func Then[A any, B any](t Task[A], f function.MapLazyErr[A, B]) Task[B]
-
Sequence: Takes multiple
Tasks and returns aTaskcontaining a slice of results, or an error if anyTaskfails.func Sequence[A any](ts ...Task[A]) Task[[]A]
-
Traverse: Applies a function to each element in a list, transforming them into
Tasks, and collects the results in a singleTask.func Traverse[A, B any](ts []A, f function.Mapping[A, Task[B]]) Task[[]B]
- ToResult: Converts a
Taskto aResult, representing either success or failure.func (t Task[A]) ToResult() result.Result[A]
package main
import (
"fmt"
"github.com/venil7/func/task"
)
func main() {
// Creating a successful task
t1 := task.Of(42)
// Creating a failing task
t2 := task.Fail[int](fmt.Errorf("some error"))
// Mapping over a task
t3 := task.Map(t1, func(i int) string { return fmt.Sprintf("Result: %d", i) })
// Running a sequence of tasks
result, err := t3()
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}This package is licensed under the MIT License. See LICENSE for details.