mirror of
https://github.com/IBM/fp-go.git
synced 2026-01-19 00:57:20 +02:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9021a8e274 | ||
|
|
f3128e887b | ||
|
|
4583694211 |
@@ -16,7 +16,11 @@
|
||||
package array
|
||||
|
||||
import (
|
||||
"github.com/IBM/fp-go/v2/internal/apply"
|
||||
"github.com/IBM/fp-go/v2/internal/array"
|
||||
"github.com/IBM/fp-go/v2/internal/functor"
|
||||
"github.com/IBM/fp-go/v2/internal/pointed"
|
||||
"github.com/IBM/fp-go/v2/internal/traversable"
|
||||
)
|
||||
|
||||
// Traverse maps each element of an array to an effect (HKT), then collects the results
|
||||
@@ -55,9 +59,9 @@ import (
|
||||
//
|
||||
//go:inline
|
||||
func Traverse[A, B, HKTB, HKTAB, HKTRB any](
|
||||
fof func([]B) HKTRB,
|
||||
fmap func(func([]B) func(B) []B) func(HKTRB) HKTAB,
|
||||
fap func(HKTB) func(HKTAB) HKTRB,
|
||||
fof pointed.OfType[[]B, HKTRB],
|
||||
fmap functor.MapType[[]B, func(B) []B, HKTRB, HKTAB],
|
||||
fap apply.ApType[HKTB, HKTRB, HKTAB],
|
||||
|
||||
f func(A) HKTB) func([]A) HKTRB {
|
||||
return array.Traverse[[]A](fof, fmap, fap, f)
|
||||
@@ -71,7 +75,7 @@ func Traverse[A, B, HKTB, HKTAB, HKTRB any](
|
||||
//
|
||||
//go:inline
|
||||
func MonadTraverse[A, B, HKTB, HKTAB, HKTRB any](
|
||||
fof func([]B) HKTRB,
|
||||
fof pointed.OfType[[]B, HKTRB],
|
||||
fmap func(func([]B) func(B) []B) func(HKTRB) HKTAB,
|
||||
fap func(HKTB) func(HKTAB) HKTRB,
|
||||
|
||||
@@ -83,7 +87,7 @@ func MonadTraverse[A, B, HKTB, HKTAB, HKTRB any](
|
||||
|
||||
//go:inline
|
||||
func TraverseWithIndex[A, B, HKTB, HKTAB, HKTRB any](
|
||||
fof func([]B) HKTRB,
|
||||
fof pointed.OfType[[]B, HKTRB],
|
||||
fmap func(func([]B) func(B) []B) func(HKTRB) HKTAB,
|
||||
fap func(HKTB) func(HKTAB) HKTRB,
|
||||
|
||||
@@ -93,7 +97,7 @@ func TraverseWithIndex[A, B, HKTB, HKTAB, HKTRB any](
|
||||
|
||||
//go:inline
|
||||
func MonadTraverseWithIndex[A, B, HKTB, HKTAB, HKTRB any](
|
||||
fof func([]B) HKTRB,
|
||||
fof pointed.OfType[[]B, HKTRB],
|
||||
fmap func(func([]B) func(B) []B) func(HKTRB) HKTAB,
|
||||
fap func(HKTB) func(HKTAB) HKTRB,
|
||||
|
||||
@@ -102,3 +106,22 @@ func MonadTraverseWithIndex[A, B, HKTB, HKTAB, HKTRB any](
|
||||
|
||||
return array.MonadTraverseWithIndex(fof, fmap, fap, ta, f)
|
||||
}
|
||||
|
||||
func MakeTraverseType[A, B, HKT_F_B, HKT_F_T_B, HKT_F_B_T_B any]() traversable.TraverseType[A, B, []A, []B, HKT_F_B, HKT_F_T_B, HKT_F_B_T_B] {
|
||||
return func(
|
||||
// ap
|
||||
fof_b pointed.OfType[[]B, HKT_F_T_B],
|
||||
fmap_b functor.MapType[[]B, func(B) []B, HKT_F_T_B, HKT_F_B_T_B],
|
||||
fap_b apply.ApType[HKT_F_B, HKT_F_T_B, HKT_F_B_T_B],
|
||||
|
||||
) func(func(A) HKT_F_B) func([]A) HKT_F_T_B {
|
||||
return func(f func(A) HKT_F_B) func([]A) HKT_F_T_B {
|
||||
return Traverse(
|
||||
fof_b,
|
||||
fmap_b,
|
||||
fap_b,
|
||||
f,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
RIOE "github.com/IBM/fp-go/v2/context/readerioresult"
|
||||
"github.com/IBM/fp-go/v2/either"
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
N "github.com/IBM/fp-go/v2/number"
|
||||
)
|
||||
|
||||
// Example_sequenceReader_basicUsage demonstrates the basic usage of SequenceReader
|
||||
@@ -233,7 +234,7 @@ func Example_sequenceReaderResult_errorHandling() {
|
||||
ctx := context.Background()
|
||||
pipeline := F.Pipe2(
|
||||
sequenced(ctx),
|
||||
RIOE.Map(func(x int) int { return x * 2 }),
|
||||
RIOE.Map(N.Mul(2)),
|
||||
RIOE.Chain(func(x int) RIOE.ReaderIOResult[string] {
|
||||
return RIOE.Of(fmt.Sprintf("Result: %d", x))
|
||||
}),
|
||||
|
||||
246
v2/context/readerresult/IO_OPERATIONS_RATIONALE.md
Normal file
246
v2/context/readerresult/IO_OPERATIONS_RATIONALE.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Why Combining IO Operations with ReaderResult Makes Sense
|
||||
|
||||
## Overview
|
||||
|
||||
The `context/readerresult` package provides functions that combine IO operations (like `FromIO`, `ChainIOK`, `TapIOK`, etc.) with ReaderResult computations. This document explains why this combination is natural and appropriate, despite IO operations being side-effectful.
|
||||
|
||||
## Key Insight: ReaderResult is Already Effectful
|
||||
|
||||
**IMPORTANT**: Unlike pure functional Reader monads, `ReaderResult[A]` in this package is **already side-effectful** because it depends on `context.Context`.
|
||||
|
||||
### Why context.Context is Effectful
|
||||
|
||||
The `context.Context` type in Go is inherently effectful because it:
|
||||
|
||||
1. **Can be cancelled**: `ctx.Done()` returns a channel that closes when the context is cancelled
|
||||
2. **Has deadlines**: `ctx.Deadline()` returns a time when the context expires
|
||||
3. **Carries values**: `ctx.Value(key)` retrieves request-scoped values
|
||||
4. **Propagates signals**: Cancellation signals propagate across goroutines
|
||||
5. **Has observable state**: The context's state can change over time (e.g., when cancelled)
|
||||
|
||||
### Type Definition
|
||||
|
||||
```go
|
||||
type ReaderResult[A any] = func(context.Context) Result[A]
|
||||
```
|
||||
|
||||
This is **not** a pure function because:
|
||||
- The behavior can change based on the context's state
|
||||
- The context can be cancelled during execution
|
||||
- The context carries mutable, observable state
|
||||
|
||||
## Comparison with Pure Reader Monads
|
||||
|
||||
### Pure Reader (from `readerresult` package)
|
||||
|
||||
```go
|
||||
type ReaderResult[R, A any] = func(R) Result[A]
|
||||
```
|
||||
|
||||
- `R` can be any type (config, state, etc.)
|
||||
- The function is **pure** if `R` is immutable
|
||||
- No side effects unless explicitly introduced
|
||||
|
||||
### Effectful Reader (from `context/readerresult` package)
|
||||
|
||||
```go
|
||||
type ReaderResult[A any] = func(context.Context) Result[A]
|
||||
```
|
||||
|
||||
- Always depends on `context.Context`
|
||||
- **Inherently effectful** due to context's nature
|
||||
- Side effects are part of the design
|
||||
|
||||
## Why IO Operations Fit Naturally
|
||||
|
||||
Since `ReaderResult` is already effectful, combining it with IO operations is a natural fit:
|
||||
|
||||
### 1. Both Represent Side Effects
|
||||
|
||||
```go
|
||||
// IO operation - side effectful
|
||||
io := func() int {
|
||||
fmt.Println("Performing IO")
|
||||
return 42
|
||||
}
|
||||
|
||||
// ReaderResult - also side effectful (depends on context)
|
||||
rr := func(ctx context.Context) Result[int] {
|
||||
// Can check if context is cancelled (side effect)
|
||||
if ctx.Err() != nil {
|
||||
return result.Error[int](ctx.Err())
|
||||
}
|
||||
return result.Of(42)
|
||||
}
|
||||
|
||||
// Combining them is natural
|
||||
combined := FromIO(io)
|
||||
```
|
||||
|
||||
### 2. Context-Aware IO Operations
|
||||
|
||||
The combination allows IO operations to respect context cancellation:
|
||||
|
||||
```go
|
||||
// IO operation that should respect cancellation
|
||||
readFile := func(path string) ReaderResult[[]byte] {
|
||||
return func(ctx context.Context) Result[[]byte] {
|
||||
// Check cancellation before expensive IO
|
||||
if ctx.Err() != nil {
|
||||
return result.Error[[]byte](ctx.Err())
|
||||
}
|
||||
|
||||
// Perform IO operation
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return result.Error[[]byte](err)
|
||||
}
|
||||
return result.Of(data)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Practical Use Cases
|
||||
|
||||
#### Logging with Side Effects
|
||||
|
||||
```go
|
||||
// Log to external system (IO operation)
|
||||
logMetric := func(value int) func() string {
|
||||
return func() string {
|
||||
// Side effect: write to metrics system
|
||||
metrics.Record("value", value)
|
||||
return "logged"
|
||||
}
|
||||
}
|
||||
|
||||
// Use with ReaderResult
|
||||
pipeline := F.Pipe1(
|
||||
readerresult.Of(42),
|
||||
readerresult.TapIOK(logMetric),
|
||||
)
|
||||
```
|
||||
|
||||
#### Database Operations
|
||||
|
||||
```go
|
||||
// Database query (IO operation with context)
|
||||
queryDB := func(id int) ReaderResult[User] {
|
||||
return func(ctx context.Context) Result[User] {
|
||||
// Context used for timeout/cancellation
|
||||
user, err := db.QueryContext(ctx, "SELECT * FROM users WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return result.Error[User](err)
|
||||
}
|
||||
return result.Of(user)
|
||||
}
|
||||
}
|
||||
|
||||
// Chain with other operations
|
||||
pipeline := F.Pipe2(
|
||||
readerresult.Of(123),
|
||||
readerresult.Chain(queryDB),
|
||||
readerresult.TapIOK(func(user User) func() string {
|
||||
return func() string {
|
||||
log.Printf("Retrieved user: %s", user.Name)
|
||||
return "logged"
|
||||
}
|
||||
}),
|
||||
)
|
||||
```
|
||||
|
||||
#### HTTP Requests
|
||||
|
||||
```go
|
||||
// HTTP request (IO operation)
|
||||
fetchData := func(url string) ReaderResult[Response] {
|
||||
return func(ctx context.Context) Result[Response] {
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return result.Error[Response](err)
|
||||
}
|
||||
return result.Of(resp)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Functions That Combine IO with ReaderResult
|
||||
|
||||
### Lifting Functions
|
||||
|
||||
- **`FromIO[A]`**: Lifts a pure IO computation into ReaderResult
|
||||
- **`FromIOResult[A]`**: Lifts an IOResult (IO with error handling) into ReaderResult
|
||||
|
||||
### Chaining Functions
|
||||
|
||||
- **`ChainIOK[A, B]`**: Sequences a ReaderResult with an IO computation
|
||||
- **`ChainIOEitherK[A, B]`**: Sequences with an IOResult computation
|
||||
- **`ChainIOResultK[A, B]`**: Alias for ChainIOEitherK
|
||||
|
||||
### Tapping Functions (Side Effects)
|
||||
|
||||
- **`TapIOK[A, B]`**: Executes IO for side effects, preserves original value
|
||||
- **`ChainFirstIOK[A, B]`**: Same as TapIOK
|
||||
- **`MonadTapIOK[A, B]`**: Monadic version of TapIOK
|
||||
- **`MonadChainFirstIOK[A, B]`**: Monadic version of ChainFirstIOK
|
||||
|
||||
### Error Handling with IO
|
||||
|
||||
- **`TapLeftIOK[A, B]`**: Executes IO on error for side effects (logging, metrics)
|
||||
- **`ChainFirstLeftIOK[A, B]`**: Same as TapLeftIOK
|
||||
|
||||
### Reading Context from IO
|
||||
|
||||
- **`ReadIO[A]`**: Executes ReaderResult with context from IO
|
||||
- **`ReadIOEither[A]`**: Executes with context from IOResult
|
||||
- **`ReadIOResult[A]`**: Alias for ReadIOEither
|
||||
|
||||
## Design Philosophy
|
||||
|
||||
### Embrace Effectfulness
|
||||
|
||||
Rather than trying to maintain purity (which is impossible with `context.Context`), this package embraces the effectful nature of Go's context and provides tools to work with it safely and composably.
|
||||
|
||||
### Composition Over Isolation
|
||||
|
||||
The package allows you to compose effectful operations (ReaderResult + IO) in a type-safe, functional way, rather than isolating them.
|
||||
|
||||
### Practical Go Idioms
|
||||
|
||||
This approach aligns with Go's pragmatic philosophy:
|
||||
- Context is used everywhere in Go for cancellation and timeouts
|
||||
- IO operations are common and necessary
|
||||
- Combining them in a type-safe way improves code quality
|
||||
|
||||
## Contrast with Pure Functional Packages
|
||||
|
||||
### When to Use `context/readerresult` (This Package)
|
||||
|
||||
Use when you need:
|
||||
- ✅ Context cancellation and timeouts
|
||||
- ✅ Request-scoped values
|
||||
- ✅ Integration with Go's standard library (http, database/sql, etc.)
|
||||
- ✅ IO operations with error handling
|
||||
- ✅ Practical, idiomatic Go code
|
||||
|
||||
### When to Use `readerresult` (Pure Package)
|
||||
|
||||
Use when you need:
|
||||
- ✅ Pure dependency injection
|
||||
- ✅ Testable computations with simple config objects
|
||||
- ✅ No context propagation
|
||||
- ✅ Generic environment types (not limited to context.Context)
|
||||
- ✅ Purely functional composition
|
||||
|
||||
## Conclusion
|
||||
|
||||
Combining IO operations with ReaderResult in the `context/readerresult` package makes sense because:
|
||||
|
||||
1. **ReaderResult is already effectful** due to its dependency on `context.Context`
|
||||
2. **IO operations are also effectful**, making them a natural fit
|
||||
3. **The combination provides practical benefits** for real-world Go applications
|
||||
4. **It aligns with Go's pragmatic philosophy** of embracing side effects when necessary
|
||||
5. **It enables type-safe composition** of effectful operations
|
||||
|
||||
The key insight is that `context.Context` itself is a side effect, so adding more side effects (IO operations) doesn't violate any purity constraints—because there were none to begin with. This package provides tools to work with these side effects in a safe, composable, and type-safe manner.
|
||||
@@ -16,7 +16,6 @@
|
||||
package readerresult
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
E "github.com/IBM/fp-go/v2/either"
|
||||
@@ -42,7 +41,7 @@ func TestBind(t *testing.T) {
|
||||
Map(utils.GetFullName),
|
||||
)
|
||||
|
||||
assert.Equal(t, res(context.Background()), E.Of[error]("John Doe"))
|
||||
assert.Equal(t, res(t.Context()), E.Of[error]("John Doe"))
|
||||
}
|
||||
|
||||
func TestApS(t *testing.T) {
|
||||
@@ -54,5 +53,5 @@ func TestApS(t *testing.T) {
|
||||
Map(utils.GetFullName),
|
||||
)
|
||||
|
||||
assert.Equal(t, res(context.Background()), E.Of[error]("John Doe"))
|
||||
assert.Equal(t, res(t.Context()), E.Of[error]("John Doe"))
|
||||
}
|
||||
|
||||
@@ -22,7 +22,75 @@ import (
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
)
|
||||
|
||||
// withContext wraps an existing ReaderResult and performs a context check for cancellation before deletating
|
||||
// WithContext wraps an existing ReaderResult and performs a context check for cancellation
|
||||
// before delegating to the wrapped computation. This provides early cancellation detection,
|
||||
// allowing computations to fail fast when the context has been cancelled or has exceeded
|
||||
// its deadline.
|
||||
//
|
||||
// IMPORTANT: This function checks for context cancellation BEFORE executing the wrapped
|
||||
// ReaderResult. If the context is already cancelled or has exceeded its deadline, the
|
||||
// computation returns immediately with the cancellation error without executing the
|
||||
// wrapped ReaderResult.
|
||||
//
|
||||
// The function uses context.Cause(ctx) to extract the cancellation reason, which may be:
|
||||
// - context.Canceled: The context was explicitly cancelled
|
||||
// - context.DeadlineExceeded: The context's deadline was exceeded
|
||||
// - A custom error: If the context was cancelled with a cause (Go 1.20+)
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The success type of the ReaderResult
|
||||
//
|
||||
// Parameters:
|
||||
// - ma: The ReaderResult to wrap with cancellation checking
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult that checks for cancellation before executing ma
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Create a long-running computation
|
||||
// longComputation := func(ctx context.Context) result.Result[int] {
|
||||
// time.Sleep(5 * time.Second)
|
||||
// return result.Of(42)
|
||||
// }
|
||||
//
|
||||
// // Wrap with cancellation check
|
||||
// safeLongComputation := readerresult.WithContext(longComputation)
|
||||
//
|
||||
// // Cancel the context before execution
|
||||
// ctx, cancel := context.WithCancel(context.Background())
|
||||
// cancel()
|
||||
//
|
||||
// // The computation returns immediately with cancellation error
|
||||
// result := safeLongComputation(ctx)
|
||||
// // result is Left(context.Canceled) - longComputation never executes
|
||||
//
|
||||
// Example with timeout:
|
||||
//
|
||||
// fetchData := func(ctx context.Context) result.Result[string] {
|
||||
// // Simulate slow operation
|
||||
// time.Sleep(2 * time.Second)
|
||||
// return result.Of("data")
|
||||
// }
|
||||
//
|
||||
// safeFetch := readerresult.WithContext(fetchData)
|
||||
//
|
||||
// // Context with 1 second timeout
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
// defer cancel()
|
||||
//
|
||||
// time.Sleep(1500 * time.Millisecond) // Wait for timeout
|
||||
//
|
||||
// result := safeFetch(ctx)
|
||||
// // result is Left(context.DeadlineExceeded) - fetchData never executes
|
||||
//
|
||||
// Use cases:
|
||||
// - Wrapping expensive computations to enable early cancellation
|
||||
// - Preventing unnecessary work when context is already cancelled
|
||||
// - Implementing timeout-aware operations
|
||||
// - Building cancellation-aware pipelines
|
||||
//
|
||||
//go:inline
|
||||
func WithContext[A any](ma ReaderResult[A]) ReaderResult[A] {
|
||||
return func(ctx context.Context) E.Either[error, A] {
|
||||
if ctx.Err() != nil {
|
||||
@@ -32,6 +100,81 @@ func WithContext[A any](ma ReaderResult[A]) ReaderResult[A] {
|
||||
}
|
||||
}
|
||||
|
||||
// WithContextK wraps a Kleisli arrow with context cancellation checking.
|
||||
// This is a higher-order function that takes a Kleisli arrow and returns a new
|
||||
// Kleisli arrow that checks for context cancellation before executing.
|
||||
//
|
||||
// IMPORTANT: This function composes the Kleisli arrow with WithContext, ensuring
|
||||
// that the resulting ReaderResult checks for cancellation before execution. This
|
||||
// is particularly useful when building pipelines of Kleisli arrows where you want
|
||||
// cancellation checking at each step.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The input type of the Kleisli arrow
|
||||
// - B: The output type of the Kleisli arrow
|
||||
//
|
||||
// Parameters:
|
||||
// - f: The Kleisli arrow to wrap with cancellation checking
|
||||
//
|
||||
// Returns:
|
||||
// - A new Kleisli arrow that checks for cancellation before executing f
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Define a Kleisli arrow
|
||||
// processUser := func(id int) readerresult.ReaderResult[User] {
|
||||
// return func(ctx context.Context) result.Result[User] {
|
||||
// // Expensive database operation
|
||||
// return fetchUserFromDB(ctx, id)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Wrap with cancellation checking
|
||||
// safeProcessUser := readerresult.WithContextK(processUser)
|
||||
//
|
||||
// // Use in a pipeline
|
||||
// pipeline := F.Pipe1(
|
||||
// readerresult.Of(123),
|
||||
// readerresult.Chain(safeProcessUser),
|
||||
// )
|
||||
//
|
||||
// // If context is cancelled, processUser never executes
|
||||
// ctx, cancel := context.WithCancel(context.Background())
|
||||
// cancel()
|
||||
// result := pipeline(ctx) // Left(context.Canceled)
|
||||
//
|
||||
// Example with multiple steps:
|
||||
//
|
||||
// getUserK := readerresult.WithContextK(func(id int) readerresult.ReaderResult[User] {
|
||||
// return func(ctx context.Context) result.Result[User] {
|
||||
// return fetchUser(ctx, id)
|
||||
// }
|
||||
// })
|
||||
//
|
||||
// getOrdersK := readerresult.WithContextK(func(user User) readerresult.ReaderResult[[]Order] {
|
||||
// return func(ctx context.Context) result.Result[[]Order] {
|
||||
// return fetchOrders(ctx, user.ID)
|
||||
// }
|
||||
// })
|
||||
//
|
||||
// // Each step checks for cancellation
|
||||
// pipeline := F.Pipe2(
|
||||
// readerresult.Of(123),
|
||||
// readerresult.Chain(getUserK),
|
||||
// readerresult.Chain(getOrdersK),
|
||||
// )
|
||||
//
|
||||
// // If context is cancelled at any point, remaining steps don't execute
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
// defer cancel()
|
||||
// result := pipeline(ctx)
|
||||
//
|
||||
// Use cases:
|
||||
// - Building cancellation-aware pipelines
|
||||
// - Ensuring each step in a chain respects cancellation
|
||||
// - Implementing timeout-aware multi-step operations
|
||||
// - Preventing cascading failures in long pipelines
|
||||
//
|
||||
//go:inline
|
||||
func WithContextK[A, B any](f Kleisli[A, B]) Kleisli[A, B] {
|
||||
return F.Flow2(
|
||||
|
||||
418
v2/context/readerresult/cancel_test.go
Normal file
418
v2/context/readerresult/cancel_test.go
Normal file
@@ -0,0 +1,418 @@
|
||||
// Copyright (c) 2023 - 2025 IBM Corp.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package readerresult
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
E "github.com/IBM/fp-go/v2/either"
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
N "github.com/IBM/fp-go/v2/number"
|
||||
"github.com/IBM/fp-go/v2/reader"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestWithContext tests the WithContext function
|
||||
func TestWithContext(t *testing.T) {
|
||||
t.Run("executes wrapped ReaderResult when context is not cancelled", func(t *testing.T) {
|
||||
executed := false
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
executed = true
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
wrapped := WithContext(computation)
|
||||
result := wrapped(context.Background())
|
||||
|
||||
assert.True(t, executed, "computation should be executed")
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("returns cancellation error when context is cancelled", func(t *testing.T) {
|
||||
executed := false
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
executed = true
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
wrapped := WithContext(computation)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := wrapped(ctx)
|
||||
|
||||
assert.False(t, executed, "computation should not be executed when context is cancelled")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, context.Canceled, err)
|
||||
})
|
||||
|
||||
t.Run("returns deadline exceeded error when context times out", func(t *testing.T) {
|
||||
executed := false
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
executed = true
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
wrapped := WithContext(computation)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
time.Sleep(20 * time.Millisecond) // Wait for timeout
|
||||
|
||||
result := wrapped(ctx)
|
||||
|
||||
assert.False(t, executed, "computation should not be executed when context has timed out")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, context.DeadlineExceeded, err)
|
||||
})
|
||||
|
||||
t.Run("preserves errors from wrapped computation", func(t *testing.T) {
|
||||
testErr := errors.New("computation error")
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
return E.Left[int](testErr)
|
||||
}
|
||||
|
||||
wrapped := WithContext(computation)
|
||||
result := wrapped(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("prevents expensive computation when context is already cancelled", func(t *testing.T) {
|
||||
expensiveExecuted := false
|
||||
expensiveComputation := func(ctx context.Context) E.Either[error, int] {
|
||||
expensiveExecuted = true
|
||||
// Simulate expensive operation
|
||||
time.Sleep(1 * time.Second)
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
wrapped := WithContext(expensiveComputation)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
start := time.Now()
|
||||
result := wrapped(ctx)
|
||||
duration := time.Since(start)
|
||||
|
||||
assert.False(t, expensiveExecuted, "expensive computation should not execute")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
assert.Less(t, duration, 100*time.Millisecond, "should return immediately")
|
||||
})
|
||||
|
||||
t.Run("works with context.WithCancelCause", func(t *testing.T) {
|
||||
executed := false
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
executed = true
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
wrapped := WithContext(computation)
|
||||
|
||||
customErr := errors.New("custom cancellation reason")
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
cancel(customErr)
|
||||
|
||||
result := wrapped(ctx)
|
||||
|
||||
assert.False(t, executed, "computation should not be executed")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, customErr, err)
|
||||
})
|
||||
|
||||
t.Run("can be nested for multiple cancellation checks", func(t *testing.T) {
|
||||
executed := false
|
||||
computation := func(ctx context.Context) E.Either[error, int] {
|
||||
executed = true
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
doubleWrapped := WithContext(WithContext(computation))
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := doubleWrapped(ctx)
|
||||
|
||||
assert.False(t, executed, "computation should not be executed")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestWithContextK tests the WithContextK function
|
||||
func TestWithContextK(t *testing.T) {
|
||||
t.Run("wraps Kleisli arrow with cancellation checking", func(t *testing.T) {
|
||||
executed := false
|
||||
processUser := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
executed = true
|
||||
return E.Of[error]("user-" + string(rune(id+48)))
|
||||
}
|
||||
}
|
||||
|
||||
safeProcessUser := WithContextK(processUser)
|
||||
|
||||
result := safeProcessUser(123)(context.Background())
|
||||
|
||||
assert.True(t, executed, "Kleisli should be executed")
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("prevents Kleisli execution when context is cancelled", func(t *testing.T) {
|
||||
executed := false
|
||||
processUser := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
executed = true
|
||||
return E.Of[error]("user")
|
||||
}
|
||||
}
|
||||
|
||||
safeProcessUser := WithContextK(processUser)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := safeProcessUser(123)(ctx)
|
||||
|
||||
assert.False(t, executed, "Kleisli should not be executed when context is cancelled")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, context.Canceled, err)
|
||||
})
|
||||
|
||||
t.Run("works in Chain pipeline", func(t *testing.T) {
|
||||
firstExecuted := false
|
||||
secondExecuted := false
|
||||
|
||||
getUser := WithContextK(func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
firstExecuted = true
|
||||
return E.Of[error]("Alice")
|
||||
}
|
||||
})
|
||||
|
||||
getOrders := WithContextK(func(name string) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
secondExecuted = true
|
||||
return E.Of[error](5)
|
||||
}
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
Of(123),
|
||||
Chain(getUser),
|
||||
Chain(getOrders),
|
||||
)
|
||||
|
||||
result := pipeline(context.Background())
|
||||
|
||||
assert.True(t, firstExecuted, "first step should execute")
|
||||
assert.True(t, secondExecuted, "second step should execute")
|
||||
assert.Equal(t, E.Of[error](5), result)
|
||||
})
|
||||
|
||||
t.Run("stops pipeline on cancellation", func(t *testing.T) {
|
||||
firstExecuted := false
|
||||
secondExecuted := false
|
||||
|
||||
getUser := WithContextK(func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
firstExecuted = true
|
||||
return E.Of[error]("Alice")
|
||||
}
|
||||
})
|
||||
|
||||
getOrders := WithContextK(func(name string) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
secondExecuted = true
|
||||
return E.Of[error](5)
|
||||
}
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
Of(123),
|
||||
Chain(getUser),
|
||||
Chain(getOrders),
|
||||
)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := pipeline(ctx)
|
||||
|
||||
assert.False(t, firstExecuted, "first step should not execute")
|
||||
assert.False(t, secondExecuted, "second step should not execute")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("respects timeout in multi-step pipeline", func(t *testing.T) {
|
||||
step1Executed := false
|
||||
step2Executed := false
|
||||
|
||||
step1 := WithContextK(func(x int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
step1Executed = true
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
return E.Of[error](x * 2)
|
||||
}
|
||||
})
|
||||
|
||||
step2 := WithContextK(func(x int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
step2Executed = true
|
||||
return E.Of[error](x + 10)
|
||||
}
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
Of(5),
|
||||
Chain(step1),
|
||||
Chain(step2),
|
||||
)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
time.Sleep(20 * time.Millisecond) // Wait for timeout
|
||||
|
||||
result := pipeline(ctx)
|
||||
|
||||
assert.False(t, step1Executed, "step1 should not execute after timeout")
|
||||
assert.False(t, step2Executed, "step2 should not execute after timeout")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("preserves errors from Kleisli computation", func(t *testing.T) {
|
||||
testErr := errors.New("kleisli error")
|
||||
failingKleisli := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Left[string](testErr)
|
||||
}
|
||||
}
|
||||
|
||||
safeKleisli := WithContextK(failingKleisli)
|
||||
result := safeKleisli(123)(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestWithContextIntegration tests integration scenarios
|
||||
func TestWithContextIntegration(t *testing.T) {
|
||||
t.Run("WithContext in complex pipeline with multiple operations", func(t *testing.T) {
|
||||
step1Executed := false
|
||||
step2Executed := false
|
||||
step3Executed := false
|
||||
|
||||
step1 := WithContext(func(ctx context.Context) E.Either[error, int] {
|
||||
step1Executed = true
|
||||
return E.Of[error](10)
|
||||
})
|
||||
|
||||
step2 := WithContextK(func(x int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
step2Executed = true
|
||||
return E.Of[error](x * 2)
|
||||
}
|
||||
})
|
||||
|
||||
step3 := WithContext(func(ctx context.Context) E.Either[error, string] {
|
||||
step3Executed = true
|
||||
return E.Of[error]("done")
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
step1,
|
||||
Chain(step2),
|
||||
ChainTo[int](step3),
|
||||
)
|
||||
|
||||
result := pipeline(context.Background())
|
||||
|
||||
assert.True(t, step1Executed)
|
||||
assert.True(t, step2Executed)
|
||||
assert.True(t, step3Executed)
|
||||
assert.Equal(t, E.Of[error]("done"), result)
|
||||
})
|
||||
|
||||
t.Run("early cancellation prevents all subsequent operations", func(t *testing.T) {
|
||||
step1Executed := false
|
||||
step2Executed := false
|
||||
step3Executed := false
|
||||
|
||||
step1 := WithContext(func(ctx context.Context) E.Either[error, int] {
|
||||
step1Executed = true
|
||||
return E.Of[error](10)
|
||||
})
|
||||
|
||||
step2 := WithContextK(func(x int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
step2Executed = true
|
||||
return E.Of[error](x * 2)
|
||||
}
|
||||
})
|
||||
|
||||
step3 := WithContext(func(ctx context.Context) E.Either[error, string] {
|
||||
step3Executed = true
|
||||
return E.Of[error]("done")
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
step1,
|
||||
Chain(step2),
|
||||
ChainTo[int](step3),
|
||||
)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := pipeline(ctx)
|
||||
|
||||
assert.False(t, step1Executed, "no steps should execute")
|
||||
assert.False(t, step2Executed, "no steps should execute")
|
||||
assert.False(t, step3Executed, "no steps should execute")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("WithContext with Map and Chain", func(t *testing.T) {
|
||||
computation := WithContext(func(ctx context.Context) E.Either[error, int] {
|
||||
return E.Of[error](42)
|
||||
})
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
computation,
|
||||
Map(N.Mul(2)),
|
||||
Map(reader.Of[int]("result")),
|
||||
)
|
||||
|
||||
result := pipeline(context.Background())
|
||||
assert.Equal(t, E.Of[error]("result"), result)
|
||||
})
|
||||
}
|
||||
@@ -21,33 +21,299 @@ import (
|
||||
"github.com/IBM/fp-go/v2/readereither"
|
||||
)
|
||||
|
||||
// these functions curry a golang function with the context as the firsr parameter into a either reader with the context as the last parameter
|
||||
// this goes back to the advice in https://pkg.go.dev/context to put the context as a first parameter as a convention
|
||||
// Curry and Uncurry functions convert between idiomatic Go functions (with context.Context as the first parameter)
|
||||
// and functional ReaderResult/Kleisli compositions (with context.Context as the last parameter).
|
||||
//
|
||||
// This follows the Go convention from https://pkg.go.dev/context to put context as the first parameter,
|
||||
// while enabling functional composition where context is typically the last parameter.
|
||||
//
|
||||
// The curry functions transform:
|
||||
// func(context.Context, T1, T2, ...) (A, error) → func(T1) func(T2) ... ReaderResult[A]
|
||||
//
|
||||
// The uncurry functions transform:
|
||||
// func(T1) func(T2) ... ReaderResult[A] → func(context.Context, T1, T2, ...) (A, error)
|
||||
|
||||
// Curry0 converts a Go function with context and no additional parameters into a ReaderResult.
|
||||
// This is useful for adapting context-aware functions to the ReaderResult monad.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The return type of the function
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A function that takes a context and returns a value and error
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult that wraps the function
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Idiomatic Go function
|
||||
// getConfig := func(ctx context.Context) (Config, error) {
|
||||
// // Check context cancellation
|
||||
// if ctx.Err() != nil {
|
||||
// return Config{}, ctx.Err()
|
||||
// }
|
||||
// return Config{Value: 42}, nil
|
||||
// }
|
||||
//
|
||||
// // Convert to ReaderResult for functional composition
|
||||
// configRR := readerresult.Curry0(getConfig)
|
||||
// result := configRR(t.Context()) // Right(Config{Value: 42})
|
||||
//
|
||||
//go:inline
|
||||
func Curry0[A any](f func(context.Context) (A, error)) ReaderResult[A] {
|
||||
return readereither.Curry0(f)
|
||||
}
|
||||
|
||||
// Curry1 converts a Go function with context and one parameter into a Kleisli arrow.
|
||||
// This enables functional composition of single-parameter functions.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the first parameter
|
||||
// - A: The return type of the function
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A function that takes a context and one parameter, returning a value and error
|
||||
//
|
||||
// Returns:
|
||||
// - A Kleisli arrow that can be composed with other ReaderResult operations
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Idiomatic Go function
|
||||
// getUserByID := func(ctx context.Context, id int) (User, error) {
|
||||
// if ctx.Err() != nil {
|
||||
// return User{}, ctx.Err()
|
||||
// }
|
||||
// return User{ID: id, Name: "Alice"}, nil
|
||||
// }
|
||||
//
|
||||
// // Convert to Kleisli for functional composition
|
||||
// getUserKleisli := readerresult.Curry1(getUserByID)
|
||||
//
|
||||
// // Use in a pipeline
|
||||
// pipeline := F.Pipe1(
|
||||
// readerresult.Of(123),
|
||||
// readerresult.Chain(getUserKleisli),
|
||||
// )
|
||||
// result := pipeline(t.Context()) // Right(User{ID: 123, Name: "Alice"})
|
||||
//
|
||||
//go:inline
|
||||
func Curry1[T1, A any](f func(context.Context, T1) (A, error)) Kleisli[T1, A] {
|
||||
return readereither.Curry1(f)
|
||||
}
|
||||
|
||||
// Curry2 converts a Go function with context and two parameters into a curried function.
|
||||
// This enables partial application and functional composition of two-parameter functions.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the first parameter
|
||||
// - T2: The type of the second parameter
|
||||
// - A: The return type of the function
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A function that takes a context and two parameters, returning a value and error
|
||||
//
|
||||
// Returns:
|
||||
// - A curried function that takes T1 and returns a Kleisli arrow for T2
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Idiomatic Go function
|
||||
// updateUser := func(ctx context.Context, id int, name string) (User, error) {
|
||||
// if ctx.Err() != nil {
|
||||
// return User{}, ctx.Err()
|
||||
// }
|
||||
// return User{ID: id, Name: name}, nil
|
||||
// }
|
||||
//
|
||||
// // Convert to curried form
|
||||
// updateUserCurried := readerresult.Curry2(updateUser)
|
||||
//
|
||||
// // Partial application
|
||||
// updateUser123 := updateUserCurried(123)
|
||||
//
|
||||
// // Use in a pipeline
|
||||
// pipeline := F.Pipe1(
|
||||
// readerresult.Of("Bob"),
|
||||
// readerresult.Chain(updateUser123),
|
||||
// )
|
||||
// result := pipeline(t.Context()) // Right(User{ID: 123, Name: "Bob"})
|
||||
//
|
||||
//go:inline
|
||||
func Curry2[T1, T2, A any](f func(context.Context, T1, T2) (A, error)) func(T1) Kleisli[T2, A] {
|
||||
return readereither.Curry2(f)
|
||||
}
|
||||
|
||||
// Curry3 converts a Go function with context and three parameters into a curried function.
|
||||
// This enables partial application and functional composition of three-parameter functions.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the first parameter
|
||||
// - T2: The type of the second parameter
|
||||
// - T3: The type of the third parameter
|
||||
// - A: The return type of the function
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A function that takes a context and three parameters, returning a value and error
|
||||
//
|
||||
// Returns:
|
||||
// - A curried function that takes T1, T2, and returns a Kleisli arrow for T3
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Idiomatic Go function
|
||||
// createOrder := func(ctx context.Context, userID int, productID int, quantity int) (Order, error) {
|
||||
// if ctx.Err() != nil {
|
||||
// return Order{}, ctx.Err()
|
||||
// }
|
||||
// return Order{UserID: userID, ProductID: productID, Quantity: quantity}, nil
|
||||
// }
|
||||
//
|
||||
// // Convert to curried form
|
||||
// createOrderCurried := readerresult.Curry3(createOrder)
|
||||
//
|
||||
// // Partial application
|
||||
// createOrderForUser := createOrderCurried(123)
|
||||
// createOrderForProduct := createOrderForUser(456)
|
||||
//
|
||||
// // Use in a pipeline
|
||||
// pipeline := F.Pipe1(
|
||||
// readerresult.Of(2),
|
||||
// readerresult.Chain(createOrderForProduct),
|
||||
// )
|
||||
// result := pipeline(t.Context()) // Right(Order{UserID: 123, ProductID: 456, Quantity: 2})
|
||||
//
|
||||
//go:inline
|
||||
func Curry3[T1, T2, T3, A any](f func(context.Context, T1, T2, T3) (A, error)) func(T1) func(T2) Kleisli[T3, A] {
|
||||
return readereither.Curry3(f)
|
||||
}
|
||||
|
||||
// Uncurry1 converts a Kleisli arrow back into an idiomatic Go function with context as the first parameter.
|
||||
// This is useful for interfacing with code that expects standard Go function signatures.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the parameter
|
||||
// - A: The return type
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A Kleisli arrow
|
||||
//
|
||||
// Returns:
|
||||
// - A Go function with context as the first parameter
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Kleisli arrow
|
||||
// getUserKleisli := func(id int) readerresult.ReaderResult[User] {
|
||||
// return func(ctx context.Context) result.Result[User] {
|
||||
// if ctx.Err() != nil {
|
||||
// return result.Error[User](ctx.Err())
|
||||
// }
|
||||
// return result.Of(User{ID: id, Name: "Alice"})
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Convert back to idiomatic Go function
|
||||
// getUserByID := readerresult.Uncurry1(getUserKleisli)
|
||||
//
|
||||
// // Use as a normal Go function
|
||||
// user, err := getUserByID(t.Context(), 123)
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// fmt.Println(user.Name) // "Alice"
|
||||
//
|
||||
//go:inline
|
||||
func Uncurry1[T1, A any](f Kleisli[T1, A]) func(context.Context, T1) (A, error) {
|
||||
return readereither.Uncurry1(f)
|
||||
}
|
||||
|
||||
// Uncurry2 converts a curried function back into an idiomatic Go function with context as the first parameter.
|
||||
// This is useful for interfacing with code that expects standard Go function signatures.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the first parameter
|
||||
// - T2: The type of the second parameter
|
||||
// - A: The return type
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A curried function
|
||||
//
|
||||
// Returns:
|
||||
// - A Go function with context as the first parameter
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Curried function
|
||||
// updateUserCurried := func(id int) func(name string) readerresult.ReaderResult[User] {
|
||||
// return func(name string) readerresult.ReaderResult[User] {
|
||||
// return func(ctx context.Context) result.Result[User] {
|
||||
// if ctx.Err() != nil {
|
||||
// return result.Error[User](ctx.Err())
|
||||
// }
|
||||
// return result.Of(User{ID: id, Name: name})
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Convert back to idiomatic Go function
|
||||
// updateUser := readerresult.Uncurry2(updateUserCurried)
|
||||
//
|
||||
// // Use as a normal Go function
|
||||
// user, err := updateUser(t.Context(), 123, "Bob")
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// fmt.Println(user.Name) // "Bob"
|
||||
//
|
||||
//go:inline
|
||||
func Uncurry2[T1, T2, A any](f func(T1) Kleisli[T2, A]) func(context.Context, T1, T2) (A, error) {
|
||||
return readereither.Uncurry2(f)
|
||||
}
|
||||
|
||||
// Uncurry3 converts a curried function back into an idiomatic Go function with context as the first parameter.
|
||||
// This is useful for interfacing with code that expects standard Go function signatures.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - T1: The type of the first parameter
|
||||
// - T2: The type of the second parameter
|
||||
// - T3: The type of the third parameter
|
||||
// - A: The return type
|
||||
//
|
||||
// Parameters:
|
||||
// - f: A curried function
|
||||
//
|
||||
// Returns:
|
||||
// - A Go function with context as the first parameter
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // Curried function
|
||||
// createOrderCurried := func(userID int) func(productID int) func(quantity int) readerresult.ReaderResult[Order] {
|
||||
// return func(productID int) func(quantity int) readerresult.ReaderResult[Order] {
|
||||
// return func(quantity int) readerresult.ReaderResult[Order] {
|
||||
// return func(ctx context.Context) result.Result[Order] {
|
||||
// if ctx.Err() != nil {
|
||||
// return result.Error[Order](ctx.Err())
|
||||
// }
|
||||
// return result.Of(Order{UserID: userID, ProductID: productID, Quantity: quantity})
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Convert back to idiomatic Go function
|
||||
// createOrder := readerresult.Uncurry3(createOrderCurried)
|
||||
//
|
||||
// // Use as a normal Go function
|
||||
// order, err := createOrder(t.Context(), 123, 456, 2)
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// fmt.Printf("Order: User=%d, Product=%d, Qty=%d\n", order.UserID, order.ProductID, order.Quantity)
|
||||
//
|
||||
//go:inline
|
||||
func Uncurry3[T1, T2, T3, A any](f func(T1) func(T2) Kleisli[T3, A]) func(context.Context, T1, T2, T3) (A, error) {
|
||||
return readereither.Uncurry3(f)
|
||||
}
|
||||
|
||||
564
v2/context/readerresult/curry_test.go
Normal file
564
v2/context/readerresult/curry_test.go
Normal file
@@ -0,0 +1,564 @@
|
||||
// Copyright (c) 2023 - 2025 IBM Corp.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package readerresult
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
E "github.com/IBM/fp-go/v2/either"
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestCurry0 tests the Curry0 function
|
||||
func TestCurry0(t *testing.T) {
|
||||
t.Run("converts Go function to ReaderResult on success", func(t *testing.T) {
|
||||
// Idiomatic Go function
|
||||
getConfig := func(ctx context.Context) (int, error) {
|
||||
return 42, nil
|
||||
}
|
||||
|
||||
// Convert to ReaderResult
|
||||
configRR := Curry0(getConfig)
|
||||
result := configRR(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("converts Go function to ReaderResult on error", func(t *testing.T) {
|
||||
testErr := errors.New("config error")
|
||||
getConfig := func(ctx context.Context) (int, error) {
|
||||
return 0, testErr
|
||||
}
|
||||
|
||||
configRR := Curry0(getConfig)
|
||||
result := configRR(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
getConfig := func(ctx context.Context) (int, error) {
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
return 42, nil
|
||||
}
|
||||
|
||||
configRR := Curry0(getConfig)
|
||||
|
||||
// Test with cancelled context
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result := configRR(ctx)
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("can be used in functional composition", func(t *testing.T) {
|
||||
getConfig := func(ctx context.Context) (int, error) {
|
||||
return 42, nil
|
||||
}
|
||||
|
||||
pipeline := F.Pipe1(
|
||||
Curry0(getConfig),
|
||||
Map(func(x int) string {
|
||||
return "value"
|
||||
}),
|
||||
)
|
||||
|
||||
result := pipeline(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestCurry1 tests the Curry1 function
|
||||
func TestCurry1(t *testing.T) {
|
||||
t.Run("converts Go function to Kleisli on success", func(t *testing.T) {
|
||||
getUserByID := func(ctx context.Context, id int) (string, error) {
|
||||
return "Alice", nil
|
||||
}
|
||||
|
||||
getUserKleisli := Curry1(getUserByID)
|
||||
|
||||
// Use in a pipeline
|
||||
pipeline := F.Pipe1(
|
||||
Of(123),
|
||||
Chain(getUserKleisli),
|
||||
)
|
||||
|
||||
result := pipeline(t.Context())
|
||||
assert.Equal(t, E.Of[error]("Alice"), result)
|
||||
})
|
||||
|
||||
t.Run("converts Go function to Kleisli on error", func(t *testing.T) {
|
||||
testErr := errors.New("user not found")
|
||||
getUserByID := func(ctx context.Context, id int) (string, error) {
|
||||
return "", testErr
|
||||
}
|
||||
|
||||
getUserKleisli := Curry1(getUserByID)
|
||||
result := getUserKleisli(123)(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
getUserByID := func(ctx context.Context, id int) (string, error) {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return "Alice", nil
|
||||
}
|
||||
|
||||
getUserKleisli := Curry1(getUserByID)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result := getUserKleisli(123)(ctx)
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("can be composed with other operations", func(t *testing.T) {
|
||||
getUserByID := func(ctx context.Context, id int) (string, error) {
|
||||
return "Alice", nil
|
||||
}
|
||||
|
||||
pipeline := F.Pipe2(
|
||||
Of(123),
|
||||
Chain(Curry1(getUserByID)),
|
||||
Map(func(name string) int {
|
||||
return len(name)
|
||||
}),
|
||||
)
|
||||
|
||||
result := pipeline(t.Context())
|
||||
assert.Equal(t, E.Of[error](5), result) // len("Alice") = 5
|
||||
})
|
||||
}
|
||||
|
||||
// TestCurry2 tests the Curry2 function
|
||||
func TestCurry2(t *testing.T) {
|
||||
t.Run("converts Go function to curried form on success", func(t *testing.T) {
|
||||
updateUser := func(ctx context.Context, id int, name string) (string, error) {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
updateUserCurried := Curry2(updateUser)
|
||||
|
||||
// Partial application
|
||||
updateUser123 := updateUserCurried(123)
|
||||
|
||||
// Use in a pipeline
|
||||
pipeline := F.Pipe1(
|
||||
Of("Bob"),
|
||||
Chain(updateUser123),
|
||||
)
|
||||
|
||||
result := pipeline(t.Context())
|
||||
assert.Equal(t, E.Of[error]("Bob"), result)
|
||||
})
|
||||
|
||||
t.Run("converts Go function to curried form on error", func(t *testing.T) {
|
||||
testErr := errors.New("update failed")
|
||||
updateUser := func(ctx context.Context, id int, name string) (string, error) {
|
||||
return "", testErr
|
||||
}
|
||||
|
||||
updateUserCurried := Curry2(updateUser)
|
||||
result := updateUserCurried(123)("Bob")(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("supports partial application", func(t *testing.T) {
|
||||
concat := func(ctx context.Context, a string, b string) (string, error) {
|
||||
return a + b, nil
|
||||
}
|
||||
|
||||
concatCurried := Curry2(concat)
|
||||
|
||||
// Partial application
|
||||
prependHello := concatCurried("Hello, ")
|
||||
|
||||
result1 := prependHello("World")(t.Context())
|
||||
result2 := prependHello("Alice")(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error]("Hello, World"), result1)
|
||||
assert.Equal(t, E.Of[error]("Hello, Alice"), result2)
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
updateUser := func(ctx context.Context, id int, name string) (string, error) {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
updateUserCurried := Curry2(updateUser)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result := updateUserCurried(123)("Bob")(ctx)
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestCurry3 tests the Curry3 function
|
||||
func TestCurry3(t *testing.T) {
|
||||
t.Run("converts Go function to curried form on success", func(t *testing.T) {
|
||||
createOrder := func(ctx context.Context, userID int, productID int, quantity int) (int, error) {
|
||||
return userID + productID + quantity, nil
|
||||
}
|
||||
|
||||
createOrderCurried := Curry3(createOrder)
|
||||
|
||||
// Partial application
|
||||
createOrderForUser := createOrderCurried(100)
|
||||
createOrderForProduct := createOrderForUser(200)
|
||||
|
||||
// Use in a pipeline
|
||||
pipeline := F.Pipe1(
|
||||
Of(3),
|
||||
Chain(createOrderForProduct),
|
||||
)
|
||||
|
||||
result := pipeline(t.Context())
|
||||
assert.Equal(t, E.Of[error](303), result) // 100 + 200 + 3
|
||||
})
|
||||
|
||||
t.Run("converts Go function to curried form on error", func(t *testing.T) {
|
||||
testErr := errors.New("order creation failed")
|
||||
createOrder := func(ctx context.Context, userID int, productID int, quantity int) (int, error) {
|
||||
return 0, testErr
|
||||
}
|
||||
|
||||
createOrderCurried := Curry3(createOrder)
|
||||
result := createOrderCurried(100)(200)(3)(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("supports multiple levels of partial application", func(t *testing.T) {
|
||||
sum3 := func(ctx context.Context, a int, b int, c int) (int, error) {
|
||||
return a + b + c, nil
|
||||
}
|
||||
|
||||
sum3Curried := Curry3(sum3)
|
||||
|
||||
// First level partial application
|
||||
add10 := sum3Curried(10)
|
||||
|
||||
// Second level partial application
|
||||
add10And20 := add10(20)
|
||||
|
||||
result1 := add10And20(5)(t.Context())
|
||||
result2 := add10And20(15)(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error](35), result1) // 10 + 20 + 5
|
||||
assert.Equal(t, E.Of[error](45), result2) // 10 + 20 + 15
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
createOrder := func(ctx context.Context, userID int, productID int, quantity int) (int, error) {
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
return userID + productID + quantity, nil
|
||||
}
|
||||
|
||||
createOrderCurried := Curry3(createOrder)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result := createOrderCurried(100)(200)(3)(ctx)
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestUncurry1 tests the Uncurry1 function
|
||||
func TestUncurry1(t *testing.T) {
|
||||
t.Run("converts Kleisli back to Go function on success", func(t *testing.T) {
|
||||
getUserKleisli := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Of[error]("Alice")
|
||||
}
|
||||
}
|
||||
|
||||
getUserByID := Uncurry1(getUserKleisli)
|
||||
|
||||
user, err := getUserByID(t.Context(), 123)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Alice", user)
|
||||
})
|
||||
|
||||
t.Run("converts Kleisli back to Go function on error", func(t *testing.T) {
|
||||
testErr := errors.New("user not found")
|
||||
getUserKleisli := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Left[string](testErr)
|
||||
}
|
||||
}
|
||||
|
||||
getUserByID := Uncurry1(getUserKleisli)
|
||||
|
||||
user, err := getUserByID(t.Context(), 123)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, testErr, err)
|
||||
assert.Equal(t, "", user)
|
||||
})
|
||||
|
||||
t.Run("respects context in uncurried function", func(t *testing.T) {
|
||||
getUserKleisli := func(id int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
if ctx.Err() != nil {
|
||||
return E.Left[string](ctx.Err())
|
||||
}
|
||||
return E.Of[error]("Alice")
|
||||
}
|
||||
}
|
||||
|
||||
getUserByID := Uncurry1(getUserKleisli)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
user, err := getUserByID(ctx, 123)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "", user)
|
||||
})
|
||||
|
||||
t.Run("round-trip with Curry1", func(t *testing.T) {
|
||||
// Original Go function
|
||||
original := func(ctx context.Context, id int) (string, error) {
|
||||
return "Alice", nil
|
||||
}
|
||||
|
||||
// Curry then uncurry
|
||||
roundTrip := Uncurry1(Curry1(original))
|
||||
|
||||
user, err := roundTrip(t.Context(), 123)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Alice", user)
|
||||
})
|
||||
}
|
||||
|
||||
// TestUncurry2 tests the Uncurry2 function
|
||||
func TestUncurry2(t *testing.T) {
|
||||
t.Run("converts curried function back to Go function on success", func(t *testing.T) {
|
||||
updateUserCurried := func(id int) func(name string) ReaderResult[string] {
|
||||
return func(name string) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Of[error](name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateUser := Uncurry2(updateUserCurried)
|
||||
|
||||
result, err := updateUser(t.Context(), 123, "Bob")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Bob", result)
|
||||
})
|
||||
|
||||
t.Run("converts curried function back to Go function on error", func(t *testing.T) {
|
||||
testErr := errors.New("update failed")
|
||||
updateUserCurried := func(id int) func(name string) ReaderResult[string] {
|
||||
return func(name string) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Left[string](testErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateUser := Uncurry2(updateUserCurried)
|
||||
|
||||
result, err := updateUser(t.Context(), 123, "Bob")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, testErr, err)
|
||||
assert.Equal(t, "", result)
|
||||
})
|
||||
|
||||
t.Run("respects context in uncurried function", func(t *testing.T) {
|
||||
updateUserCurried := func(id int) func(name string) ReaderResult[string] {
|
||||
return func(name string) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
if ctx.Err() != nil {
|
||||
return E.Left[string](ctx.Err())
|
||||
}
|
||||
return E.Of[error](name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateUser := Uncurry2(updateUserCurried)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
result, err := updateUser(ctx, 123, "Bob")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "", result)
|
||||
})
|
||||
|
||||
t.Run("round-trip with Curry2", func(t *testing.T) {
|
||||
// Original Go function
|
||||
original := func(ctx context.Context, a string, b string) (string, error) {
|
||||
return a + b, nil
|
||||
}
|
||||
|
||||
// Curry then uncurry
|
||||
roundTrip := Uncurry2(Curry2(original))
|
||||
|
||||
result, err := roundTrip(t.Context(), "Hello, ", "World")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Hello, World", result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestUncurry3 tests the Uncurry3 function
|
||||
func TestUncurry3(t *testing.T) {
|
||||
t.Run("converts curried function back to Go function on success", func(t *testing.T) {
|
||||
createOrderCurried := func(userID int) func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(quantity int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
return E.Of[error](userID + productID + quantity)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createOrder := Uncurry3(createOrderCurried)
|
||||
|
||||
result, err := createOrder(t.Context(), 100, 200, 3)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 303, result) // 100 + 200 + 3
|
||||
})
|
||||
|
||||
t.Run("converts curried function back to Go function on error", func(t *testing.T) {
|
||||
testErr := errors.New("order creation failed")
|
||||
createOrderCurried := func(userID int) func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(quantity int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
return E.Left[int](testErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createOrder := Uncurry3(createOrderCurried)
|
||||
|
||||
result, err := createOrder(t.Context(), 100, 200, 3)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, testErr, err)
|
||||
assert.Equal(t, 0, result)
|
||||
})
|
||||
|
||||
t.Run("respects context in uncurried function", func(t *testing.T) {
|
||||
createOrderCurried := func(userID int) func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(productID int) func(quantity int) ReaderResult[int] {
|
||||
return func(quantity int) ReaderResult[int] {
|
||||
return func(ctx context.Context) E.Either[error, int] {
|
||||
if ctx.Err() != nil {
|
||||
return E.Left[int](ctx.Err())
|
||||
}
|
||||
return E.Of[error](userID + productID + quantity)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createOrder := Uncurry3(createOrderCurried)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
result, err := createOrder(ctx, 100, 200, 3)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, 0, result)
|
||||
})
|
||||
|
||||
t.Run("round-trip with Curry3", func(t *testing.T) {
|
||||
// Original Go function
|
||||
original := func(ctx context.Context, a int, b int, c int) (int, error) {
|
||||
return a + b + c, nil
|
||||
}
|
||||
|
||||
// Curry then uncurry
|
||||
roundTrip := Uncurry3(Curry3(original))
|
||||
|
||||
result, err := roundTrip(t.Context(), 10, 20, 5)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 35, result) // 10 + 20 + 5
|
||||
})
|
||||
}
|
||||
|
||||
// TestCurryUncurryIntegration tests integration between curry and uncurry functions
|
||||
func TestCurryUncurryIntegration(t *testing.T) {
|
||||
t.Run("Curry1 and Uncurry1 are inverses", func(t *testing.T) {
|
||||
original := func(ctx context.Context, x int) (int, error) {
|
||||
return x * 2, nil
|
||||
}
|
||||
|
||||
// Curry then uncurry should give back equivalent function
|
||||
roundTrip := Uncurry1(Curry1(original))
|
||||
|
||||
result1, err1 := original(t.Context(), 21)
|
||||
result2, err2 := roundTrip(t.Context(), 21)
|
||||
|
||||
assert.NoError(t, err1)
|
||||
assert.NoError(t, err2)
|
||||
assert.Equal(t, result1, result2)
|
||||
})
|
||||
|
||||
t.Run("Curry2 and Uncurry2 are inverses", func(t *testing.T) {
|
||||
original := func(ctx context.Context, x int, y int) (int, error) {
|
||||
return x + y, nil
|
||||
}
|
||||
|
||||
roundTrip := Uncurry2(Curry2(original))
|
||||
|
||||
result1, err1 := original(t.Context(), 10, 20)
|
||||
result2, err2 := roundTrip(t.Context(), 10, 20)
|
||||
|
||||
assert.NoError(t, err1)
|
||||
assert.NoError(t, err2)
|
||||
assert.Equal(t, result1, result2)
|
||||
})
|
||||
|
||||
t.Run("Curry3 and Uncurry3 are inverses", func(t *testing.T) {
|
||||
original := func(ctx context.Context, x int, y int, z int) (int, error) {
|
||||
return x * y * z, nil
|
||||
}
|
||||
|
||||
roundTrip := Uncurry3(Curry3(original))
|
||||
|
||||
result1, err1 := original(t.Context(), 2, 3, 4)
|
||||
result2, err2 := roundTrip(t.Context(), 2, 3, 4)
|
||||
|
||||
assert.NoError(t, err1)
|
||||
assert.NoError(t, err2)
|
||||
assert.Equal(t, result1, result2)
|
||||
})
|
||||
}
|
||||
@@ -43,7 +43,7 @@ import (
|
||||
// onNegative := func(n int) error { return fmt.Errorf("%d is not positive", n) }
|
||||
//
|
||||
// filter := readerresult.FilterOrElse(isPositive, onNegative)
|
||||
// result := filter(readerresult.Right(42))(context.Background())
|
||||
// result := filter(readerresult.Right(42))(t.Context())
|
||||
//
|
||||
//go:inline
|
||||
func FilterOrElse[A any](pred Predicate[A], onFalse func(A) error) Operator[A, A] {
|
||||
|
||||
@@ -63,7 +63,7 @@ import (
|
||||
// // Sequenced: takes context first, then Database
|
||||
// sequenced := SequenceReader(original)
|
||||
//
|
||||
// ctx := context.Background()
|
||||
// ctx := t.Context()
|
||||
// db := Database{ConnectionString: "localhost:5432"}
|
||||
//
|
||||
// // Apply context first to get a function that takes database
|
||||
@@ -135,7 +135,7 @@ func SequenceReader[R, A any](ma ReaderResult[Reader[R, A]]) reader.Kleisli[cont
|
||||
//
|
||||
// // Now we can provide Config first, then context
|
||||
// cfg := Config{MaxRetries: 3}
|
||||
// ctx := context.Background()
|
||||
// ctx := t.Context()
|
||||
//
|
||||
// result := flipped(cfg)(ctx)
|
||||
// // result is Result[string] containing "Value: 42, MaxRetries: 3"
|
||||
|
||||
@@ -96,7 +96,7 @@ func curriedLog(
|
||||
// logDebug := SLogWithCallback[User](slog.LevelDebug, getLogger, "User data")
|
||||
//
|
||||
// // Use in a pipeline
|
||||
// ctx := context.Background()
|
||||
// ctx := t.Context()
|
||||
// user := result.Of(User{ID: 123, Name: "Alice"})
|
||||
// logged := logDebug(user)(ctx) // Logs: level=DEBUG msg="User data" value={ID:123 Name:Alice}
|
||||
// // logged still contains the User value
|
||||
@@ -149,7 +149,7 @@ func SLogWithCallback[A any](
|
||||
//
|
||||
// Example - Logging a successful computation:
|
||||
//
|
||||
// ctx := context.Background()
|
||||
// ctx := t.Context()
|
||||
//
|
||||
// // Simple value logging
|
||||
// res := result.Of(42)
|
||||
@@ -172,7 +172,7 @@ func SLogWithCallback[A any](
|
||||
// return result.Of(fmt.Sprintf("Processed: %s", user.Name))
|
||||
// }
|
||||
//
|
||||
// ctx := context.Background()
|
||||
// ctx := t.Context()
|
||||
//
|
||||
// // Log at each step
|
||||
// userResult := fetchUser(123)
|
||||
@@ -195,7 +195,7 @@ func SLogWithCallback[A any](
|
||||
//
|
||||
// // Set up a custom logger in the context
|
||||
// logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
// ctx := logging.WithLogger(logger)(context.Background())
|
||||
// ctx := logging.WithLogger(logger)(t.Context())
|
||||
//
|
||||
// res := result.Of("important data")
|
||||
// logged := SLog[string]("Critical operation")(res)(ctx)
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestSLogLogsSuccessValue(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// Create a Result and log it
|
||||
res1 := result.Of(42)
|
||||
@@ -59,7 +59,7 @@ func TestSLogLogsErrorValue(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
testErr := errors.New("test error")
|
||||
|
||||
// Create an error Result and log it
|
||||
@@ -83,7 +83,7 @@ func TestSLogInPipeline(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// SLog takes a Result[A] and returns ReaderResult[A]
|
||||
// So we need to start with a Result, apply SLog, then execute with context
|
||||
@@ -104,7 +104,7 @@ func TestSLogWithContextLogger(t *testing.T) {
|
||||
Level: slog.LevelInfo,
|
||||
}))
|
||||
|
||||
ctx := logging.WithLogger(contextLogger)(context.Background())
|
||||
ctx := logging.WithLogger(contextLogger)(t.Context())
|
||||
|
||||
res1 := result.Of("test value")
|
||||
logged := SLog[string]("Context logger test")(res1)(ctx)
|
||||
@@ -126,7 +126,7 @@ func TestSLogDisabled(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
res1 := result.Of(42)
|
||||
logged := SLog[int]("This should not be logged")(res1)(ctx)
|
||||
@@ -152,7 +152,7 @@ func TestSLogWithStruct(t *testing.T) {
|
||||
Name string
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
user := User{ID: 123, Name: "Alice"}
|
||||
|
||||
res1 := result.Of(user)
|
||||
@@ -177,7 +177,7 @@ func TestSLogWithCallbackCustomLevel(t *testing.T) {
|
||||
return logger
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// Create a Result and log it with custom callback
|
||||
res1 := result.Of(42)
|
||||
@@ -202,7 +202,7 @@ func TestSLogWithCallbackLogsError(t *testing.T) {
|
||||
return logger
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
testErr := errors.New("warning error")
|
||||
|
||||
// Create an error Result and log it with custom callback
|
||||
@@ -227,7 +227,7 @@ func TestSLogChainedOperations(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// First log step 1
|
||||
res1 := result.Of(5)
|
||||
@@ -255,7 +255,7 @@ func TestSLogPreservesError(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
testErr := errors.New("original error")
|
||||
|
||||
res1 := result.Left[int](testErr)
|
||||
@@ -280,7 +280,7 @@ func TestSLogMultipleValues(t *testing.T) {
|
||||
oldLogger := logging.SetLogger(logger)
|
||||
defer logging.SetLogger(oldLogger)
|
||||
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// Test with different types
|
||||
intRes := SLog[int]("Integer")(result.Of(42))(ctx)
|
||||
|
||||
@@ -41,7 +41,7 @@ func TestPromapBasic(t *testing.T) {
|
||||
toString := strconv.Itoa
|
||||
|
||||
adapted := Promap(addKey, toString)(getValue)
|
||||
result := adapted(context.Background())
|
||||
result := adapted(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of("42"), result)
|
||||
})
|
||||
@@ -63,7 +63,7 @@ func TestContramapBasic(t *testing.T) {
|
||||
}
|
||||
|
||||
adapted := Contramap[int](addKey)(getValue)
|
||||
result := adapted(context.Background())
|
||||
result := adapted(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(100), result)
|
||||
})
|
||||
@@ -85,7 +85,7 @@ func TestLocalBasic(t *testing.T) {
|
||||
}
|
||||
|
||||
adapted := Local[string](addUser)(getValue)
|
||||
result := adapted(context.Background())
|
||||
result := adapted(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of("Alice"), result)
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,7 @@ import (
|
||||
|
||||
E "github.com/IBM/fp-go/v2/either"
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
"github.com/IBM/fp-go/v2/option"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -38,7 +39,7 @@ func TestMapTo(t *testing.T) {
|
||||
resultReader := toDone(originalReader)
|
||||
|
||||
// Execute the resulting reader
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
// Verify the constant value is returned
|
||||
assert.Equal(t, E.Of[error]("done"), result)
|
||||
@@ -58,7 +59,7 @@ func TestMapTo(t *testing.T) {
|
||||
MapTo[int]("complete"),
|
||||
)
|
||||
|
||||
result := pipeline(context.Background())
|
||||
result := pipeline(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error]("complete"), result)
|
||||
assert.True(t, executed, "original reader should be executed in pipeline")
|
||||
@@ -72,7 +73,7 @@ func TestMapTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MapTo[int](true)(readerWithSideEffect)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error](true), result)
|
||||
assert.True(t, sideEffectOccurred, "side effect should occur")
|
||||
@@ -87,7 +88,7 @@ func TestMapTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MapTo[int]("done")(failingReader)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
assert.True(t, executed, "failing reader should still be executed")
|
||||
@@ -106,7 +107,7 @@ func TestMonadMapTo(t *testing.T) {
|
||||
resultReader := MonadMapTo(originalReader, "done")
|
||||
|
||||
// Execute the resulting reader
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
// Verify the constant value is returned
|
||||
assert.Equal(t, E.Of[error]("done"), result)
|
||||
@@ -122,7 +123,7 @@ func TestMonadMapTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MonadMapTo(complexReader, 42)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, computationExecuted, "complex computation should be executed")
|
||||
@@ -137,7 +138,7 @@ func TestMonadMapTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MonadMapTo(failingReader, 99)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
assert.True(t, executed, "failing reader should still be executed")
|
||||
@@ -164,7 +165,7 @@ func TestChainTo(t *testing.T) {
|
||||
resultReader := thenSecond(firstReader)
|
||||
|
||||
// Execute the resulting reader
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
// Verify the second reader's result is returned
|
||||
assert.Equal(t, E.Of[error]("result"), result)
|
||||
@@ -192,7 +193,7 @@ func TestChainTo(t *testing.T) {
|
||||
ChainTo[int](step2),
|
||||
)
|
||||
|
||||
result := pipeline(context.Background())
|
||||
result := pipeline(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error]("complete"), result)
|
||||
assert.True(t, firstExecuted, "first reader should be executed in pipeline")
|
||||
@@ -211,7 +212,7 @@ func TestChainTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := ChainTo[int](secondReader)(readerWithSideEffect)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error](true), result)
|
||||
assert.True(t, sideEffectOccurred, "side effect should occur in first reader")
|
||||
@@ -233,7 +234,7 @@ func TestChainTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := ChainTo[int](secondReader)(failingReader)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
assert.True(t, firstExecuted, "first reader should be executed")
|
||||
@@ -260,7 +261,7 @@ func TestMonadChainTo(t *testing.T) {
|
||||
resultReader := MonadChainTo(firstReader, secondReader)
|
||||
|
||||
// Execute the resulting reader
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
// Verify the second reader's result is returned
|
||||
assert.Equal(t, E.Of[error]("result"), result)
|
||||
@@ -284,7 +285,7 @@ func TestMonadChainTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MonadChainTo(complexFirstReader, secondReader)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Of[error]("done"), result)
|
||||
assert.True(t, firstExecuted, "complex first computation should be executed")
|
||||
@@ -307,7 +308,7 @@ func TestMonadChainTo(t *testing.T) {
|
||||
}
|
||||
|
||||
resultReader := MonadChainTo(failingReader, secondReader)
|
||||
result := resultReader(context.Background())
|
||||
result := resultReader(t.Context())
|
||||
|
||||
assert.Equal(t, E.Left[float64](testErr), result)
|
||||
assert.True(t, firstExecuted, "first reader should be executed")
|
||||
@@ -316,7 +317,7 @@ func TestMonadChainTo(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestOrElse(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
// Test OrElse with Right - should pass through unchanged
|
||||
t.Run("Right value unchanged", func(t *testing.T) {
|
||||
@@ -380,3 +381,613 @@ func TestOrElse(t *testing.T) {
|
||||
assert.Equal(t, E.Of[error](123), res)
|
||||
})
|
||||
}
|
||||
|
||||
// TestFromIO tests the FromIO function
|
||||
func TestFromIO(t *testing.T) {
|
||||
t.Run("lifts IO computation into ReaderResult", func(t *testing.T) {
|
||||
ioOp := func() int { return 42 }
|
||||
rr := FromIO(ioOp)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("executes IO side effects", func(t *testing.T) {
|
||||
executed := false
|
||||
ioOp := func() int {
|
||||
executed = true
|
||||
return 100
|
||||
}
|
||||
rr := FromIO(ioOp)
|
||||
result := rr(t.Context())
|
||||
assert.True(t, executed, "IO operation should be executed")
|
||||
assert.Equal(t, E.Of[error](100), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestFromIOResult tests the FromIOResult function
|
||||
func TestFromIOResult(t *testing.T) {
|
||||
t.Run("lifts IOResult into ReaderResult on success", func(t *testing.T) {
|
||||
ioResult := func() E.Either[error, int] {
|
||||
return E.Of[error](42)
|
||||
}
|
||||
rr := FromIOResult(ioResult)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("lifts IOResult into ReaderResult on error", func(t *testing.T) {
|
||||
testErr := errors.New("io error")
|
||||
ioResult := func() E.Either[error, int] {
|
||||
return E.Left[int](testErr)
|
||||
}
|
||||
rr := FromIOResult(ioResult)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestFromReader tests the FromReader function
|
||||
func TestFromReader(t *testing.T) {
|
||||
t.Run("lifts Reader into ReaderResult", func(t *testing.T) {
|
||||
reader := func(ctx context.Context) int {
|
||||
return 42
|
||||
}
|
||||
rr := FromReader(reader)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("Reader can access context", func(t *testing.T) {
|
||||
type ctxKey string
|
||||
ctx := context.WithValue(t.Context(), ctxKey("key"), "value")
|
||||
reader := func(ctx context.Context) string {
|
||||
return ctx.Value(ctxKey("key")).(string)
|
||||
}
|
||||
rr := FromReader(reader)
|
||||
result := rr(ctx)
|
||||
assert.Equal(t, E.Of[error]("value"), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestFromEither tests the FromEither function
|
||||
func TestFromEither(t *testing.T) {
|
||||
t.Run("lifts Right Either into ReaderResult", func(t *testing.T) {
|
||||
either := E.Of[error](42)
|
||||
rr := FromEither(either)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("lifts Left Either into ReaderResult", func(t *testing.T) {
|
||||
testErr := errors.New("test error")
|
||||
either := E.Left[int](testErr)
|
||||
rr := FromEither(either)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestLeftRight tests the Left and Right functions
|
||||
func TestLeftRight(t *testing.T) {
|
||||
t.Run("Left creates error ReaderResult", func(t *testing.T) {
|
||||
testErr := errors.New("test error")
|
||||
rr := Left[int](testErr)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("Right creates success ReaderResult", func(t *testing.T) {
|
||||
rr := Right(42)
|
||||
result := rr(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadMapAndMap tests MonadMap and Map functions
|
||||
func TestMonadMapAndMap(t *testing.T) {
|
||||
t.Run("MonadMap transforms success value", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
mapped := MonadMap(rr, func(x int) string {
|
||||
return F.Pipe1(x, func(n int) string { return "value: " + F.Pipe1(n, func(i int) string { return string(rune(i + 48)) }) })
|
||||
})
|
||||
result := mapped(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("Map creates operator that transforms value", func(t *testing.T) {
|
||||
toString := Map(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
rr := Of(42)
|
||||
result := toString(rr)(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("Map preserves errors", func(t *testing.T) {
|
||||
testErr := errors.New("test error")
|
||||
toString := Map(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
rr := Left[int](testErr)
|
||||
result := toString(rr)(t.Context())
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadChainAndChain tests MonadChain and Chain functions
|
||||
func TestMonadChainAndChain(t *testing.T) {
|
||||
t.Run("MonadChain sequences computations", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
chained := MonadChain(rr, func(x int) ReaderResult[string] {
|
||||
return Of("result")
|
||||
})
|
||||
result := chained(t.Context())
|
||||
assert.Equal(t, E.Of[error]("result"), result)
|
||||
})
|
||||
|
||||
t.Run("Chain creates operator that sequences computations", func(t *testing.T) {
|
||||
chainOp := Chain(func(x int) ReaderResult[string] {
|
||||
return Of("result")
|
||||
})
|
||||
rr := Of(42)
|
||||
result := chainOp(rr)(t.Context())
|
||||
assert.Equal(t, E.Of[error]("result"), result)
|
||||
})
|
||||
|
||||
t.Run("Chain short-circuits on error", func(t *testing.T) {
|
||||
executed := false
|
||||
testErr := errors.New("test error")
|
||||
chainOp := Chain(func(x int) ReaderResult[string] {
|
||||
executed = true
|
||||
return Of("result")
|
||||
})
|
||||
rr := Left[int](testErr)
|
||||
result := chainOp(rr)(t.Context())
|
||||
assert.False(t, executed, "Chain should not execute on error")
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAsk tests the Ask function
|
||||
func TestAsk(t *testing.T) {
|
||||
t.Run("Ask returns the context", func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
rr := Ask()
|
||||
result := rr(ctx)
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("Ask can be used in chain to access context", func(t *testing.T) {
|
||||
type ctxKey string
|
||||
ctx := context.WithValue(t.Context(), ctxKey("key"), "value")
|
||||
pipeline := F.Pipe1(
|
||||
Ask(),
|
||||
Chain(func(c context.Context) ReaderResult[string] {
|
||||
val := c.Value(ctxKey("key"))
|
||||
if val != nil {
|
||||
return Of(val.(string))
|
||||
}
|
||||
return Left[string](errors.New("key not found"))
|
||||
}),
|
||||
)
|
||||
result := pipeline(ctx)
|
||||
assert.Equal(t, E.Of[error]("value"), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadChainEitherK tests MonadChainEitherK and ChainEitherK
|
||||
func TestMonadChainEitherK(t *testing.T) {
|
||||
t.Run("MonadChainEitherK sequences with Either function", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
chained := MonadChainEitherK(rr, func(x int) E.Either[error, string] {
|
||||
if x > 0 {
|
||||
return E.Of[error]("positive")
|
||||
}
|
||||
return E.Left[string](errors.New("not positive"))
|
||||
})
|
||||
result := chained(t.Context())
|
||||
assert.Equal(t, E.Of[error]("positive"), result)
|
||||
})
|
||||
|
||||
t.Run("ChainEitherK creates operator", func(t *testing.T) {
|
||||
validate := ChainEitherK(func(x int) E.Either[error, int] {
|
||||
if x > 0 {
|
||||
return E.Of[error](x)
|
||||
}
|
||||
return E.Left[int](errors.New("must be positive"))
|
||||
})
|
||||
result := validate(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadFlap tests MonadFlap and Flap
|
||||
func TestMonadFlap(t *testing.T) {
|
||||
t.Run("MonadFlap applies value to function", func(t *testing.T) {
|
||||
fabRR := Of(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
result := MonadFlap(fabRR, 42)(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("Flap creates operator", func(t *testing.T) {
|
||||
applyTo42 := Flap[string](42)
|
||||
fabRR := Of(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
result := applyTo42(fabRR)(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestRead functions
|
||||
func TestReadFunctions(t *testing.T) {
|
||||
t.Run("Read executes ReaderResult with context", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
ctx := t.Context()
|
||||
runWithCtx := Read[int](ctx)
|
||||
result := runWithCtx(rr)
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("ReadEither executes with Result context on success", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
ctxResult := E.Of[error](t.Context())
|
||||
runWithCtxResult := ReadEither[int](ctxResult)
|
||||
result := runWithCtxResult(rr)
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("ReadEither returns error when context Result is error", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
testErr := errors.New("context error")
|
||||
ctxResult := E.Left[context.Context](testErr)
|
||||
runWithCtxResult := ReadEither[int](ctxResult)
|
||||
result := runWithCtxResult(rr)
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("ReadResult is alias for ReadEither", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
ctxResult := E.Of[error](t.Context())
|
||||
runWithCtxResult := ReadResult[int](ctxResult)
|
||||
result := runWithCtxResult(rr)
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadChainFirst tests MonadChainFirst and ChainFirst
|
||||
func TestMonadChainFirst(t *testing.T) {
|
||||
t.Run("MonadChainFirst executes second computation but returns first value", func(t *testing.T) {
|
||||
secondExecuted := false
|
||||
rr := Of(42)
|
||||
withSideEffect := MonadChainFirst(rr, func(x int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
secondExecuted = true
|
||||
return E.Of[error]("logged")
|
||||
}
|
||||
})
|
||||
result := withSideEffect(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, secondExecuted, "second computation should execute")
|
||||
})
|
||||
|
||||
t.Run("ChainFirst creates operator", func(t *testing.T) {
|
||||
secondExecuted := false
|
||||
logValue := ChainFirst(func(x int) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
secondExecuted = true
|
||||
return E.Of[error]("logged")
|
||||
}
|
||||
})
|
||||
result := logValue(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, secondExecuted)
|
||||
})
|
||||
}
|
||||
|
||||
// TestChainIOK tests ChainIOK and MonadChainIOK
|
||||
func TestChainIOK(t *testing.T) {
|
||||
t.Run("MonadChainIOK sequences with IO computation", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
rr := Of(42)
|
||||
withIO := MonadChainIOK(rr, func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "done"
|
||||
}
|
||||
})
|
||||
result := withIO(t.Context())
|
||||
assert.Equal(t, E.Of[error]("done"), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
|
||||
t.Run("ChainIOK creates operator", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
logIO := ChainIOK(func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
result := logIO(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error]("logged"), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
}
|
||||
|
||||
// TestChainFirstIOK tests ChainFirstIOK, MonadChainFirstIOK, and TapIOK
|
||||
func TestChainFirstIOK(t *testing.T) {
|
||||
t.Run("MonadChainFirstIOK executes IO but returns original value", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
rr := Of(42)
|
||||
withLog := MonadChainFirstIOK(rr, func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
result := withLog(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
|
||||
t.Run("ChainFirstIOK creates operator", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
logIO := ChainFirstIOK(func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
result := logIO(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
|
||||
t.Run("TapIOK is alias for ChainFirstIOK", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
tapLog := TapIOK(func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
result := tapLog(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
|
||||
t.Run("MonadTapIOK is alias for MonadChainFirstIOK", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
rr := Of(42)
|
||||
withLog := MonadTapIOK(rr, func(x int) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
result := withLog(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
}
|
||||
|
||||
// TestChainIOEitherK tests ChainIOEitherK and ChainIOResultK
|
||||
func TestChainIOEitherK(t *testing.T) {
|
||||
t.Run("ChainIOEitherK sequences with IOResult on success", func(t *testing.T) {
|
||||
ioResultOp := ChainIOEitherK(func(x int) func() E.Either[error, string] {
|
||||
return func() E.Either[error, string] {
|
||||
if x > 0 {
|
||||
return E.Of[error]("positive")
|
||||
}
|
||||
return E.Left[string](errors.New("not positive"))
|
||||
}
|
||||
})
|
||||
result := ioResultOp(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error]("positive"), result)
|
||||
})
|
||||
|
||||
t.Run("ChainIOEitherK propagates IOResult error", func(t *testing.T) {
|
||||
testErr := errors.New("io error")
|
||||
ioResultOp := ChainIOEitherK(func(x int) func() E.Either[error, string] {
|
||||
return func() E.Either[error, string] {
|
||||
return E.Left[string](testErr)
|
||||
}
|
||||
})
|
||||
result := ioResultOp(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Left[string](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("ChainIOResultK is alias for ChainIOEitherK", func(t *testing.T) {
|
||||
ioResultOp := ChainIOResultK(func(x int) func() E.Either[error, string] {
|
||||
return func() E.Either[error, string] {
|
||||
return E.Of[error]("value")
|
||||
}
|
||||
})
|
||||
result := ioResultOp(Of(42))(t.Context())
|
||||
assert.Equal(t, E.Of[error]("value"), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestReadIO tests ReadIO, ReadIOEither, and ReadIOResult
|
||||
func TestReadIO(t *testing.T) {
|
||||
t.Run("ReadIO executes with IO context", func(t *testing.T) {
|
||||
getCtx := func() context.Context { return t.Context() }
|
||||
rr := Of(42)
|
||||
runWithIO := ReadIO[int](getCtx)
|
||||
ioResult := runWithIO(rr)
|
||||
result := ioResult()
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("ReadIOEither executes with IOResult context on success", func(t *testing.T) {
|
||||
getCtx := func() E.Either[error, context.Context] {
|
||||
return E.Of[error](t.Context())
|
||||
}
|
||||
rr := Of(42)
|
||||
runWithIOResult := ReadIOEither[int](getCtx)
|
||||
ioResult := runWithIOResult(rr)
|
||||
result := ioResult()
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("ReadIOEither returns error when IOResult context is error", func(t *testing.T) {
|
||||
testErr := errors.New("context error")
|
||||
getCtx := func() E.Either[error, context.Context] {
|
||||
return E.Left[context.Context](testErr)
|
||||
}
|
||||
rr := Of(42)
|
||||
runWithIOResult := ReadIOEither[int](getCtx)
|
||||
ioResult := runWithIOResult(rr)
|
||||
result := ioResult()
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
})
|
||||
|
||||
t.Run("ReadIOResult is alias for ReadIOEither", func(t *testing.T) {
|
||||
getCtx := func() E.Either[error, context.Context] {
|
||||
return E.Of[error](t.Context())
|
||||
}
|
||||
rr := Of(42)
|
||||
runWithIOResult := ReadIOResult[int](getCtx)
|
||||
ioResult := runWithIOResult(rr)
|
||||
result := ioResult()
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
}
|
||||
|
||||
// TestChainFirstLeft tests ChainFirstLeft, ChainFirstLeftIOK, and TapLeftIOK
|
||||
func TestChainFirstLeft(t *testing.T) {
|
||||
t.Run("ChainFirstLeft executes on error but preserves it", func(t *testing.T) {
|
||||
errorHandled := false
|
||||
testErr := errors.New("test error")
|
||||
logError := ChainFirstLeft[int](func(err error) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
errorHandled = true
|
||||
return E.Of[error]("logged")
|
||||
}
|
||||
})
|
||||
rr := Left[int](testErr)
|
||||
result := logError(rr)(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
assert.True(t, errorHandled, "error handler should execute")
|
||||
})
|
||||
|
||||
t.Run("ChainFirstLeft does not execute on success", func(t *testing.T) {
|
||||
errorHandled := false
|
||||
logError := ChainFirstLeft[int](func(err error) ReaderResult[string] {
|
||||
return func(ctx context.Context) E.Either[error, string] {
|
||||
errorHandled = true
|
||||
return E.Of[error]("logged")
|
||||
}
|
||||
})
|
||||
rr := Of(42)
|
||||
result := logError(rr)(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
assert.False(t, errorHandled, "error handler should not execute on success")
|
||||
})
|
||||
|
||||
t.Run("ChainFirstLeftIOK executes IO on error", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
testErr := errors.New("test error")
|
||||
logErrorIO := ChainFirstLeftIOK[int](func(err error) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
rr := Left[int](testErr)
|
||||
result := logErrorIO(rr)(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
|
||||
t.Run("TapLeftIOK is alias for ChainFirstLeftIOK", func(t *testing.T) {
|
||||
ioExecuted := false
|
||||
testErr := errors.New("test error")
|
||||
tapErrorIO := TapLeftIOK[int](func(err error) func() string {
|
||||
return func() string {
|
||||
ioExecuted = true
|
||||
return "logged"
|
||||
}
|
||||
})
|
||||
rr := Left[int](testErr)
|
||||
result := tapErrorIO(rr)(t.Context())
|
||||
assert.Equal(t, E.Left[int](testErr), result)
|
||||
assert.True(t, ioExecuted)
|
||||
})
|
||||
}
|
||||
|
||||
// TestFromPredicate tests the FromPredicate function
|
||||
func TestFromPredicate(t *testing.T) {
|
||||
t.Run("FromPredicate returns Right when predicate is true", func(t *testing.T) {
|
||||
isPositive := FromPredicate(
|
||||
func(x int) bool { return x > 0 },
|
||||
func(x int) error { return errors.New("not positive") },
|
||||
)
|
||||
result := isPositive(42)(t.Context())
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
})
|
||||
|
||||
t.Run("FromPredicate returns Left when predicate is false", func(t *testing.T) {
|
||||
isPositive := FromPredicate(
|
||||
func(x int) bool { return x > 0 },
|
||||
func(x int) error { return errors.New("not positive") },
|
||||
)
|
||||
result := isPositive(-1)(t.Context())
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestMonadAp tests MonadAp and Ap
|
||||
func TestMonadAp(t *testing.T) {
|
||||
t.Run("MonadAp applies function to value", func(t *testing.T) {
|
||||
fabRR := Of(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
faRR := Of(42)
|
||||
result := MonadAp(fabRR, faRR)(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("Ap creates function that applies", func(t *testing.T) {
|
||||
faRR := Of(42)
|
||||
applyTo42 := Ap[int, string](faRR)
|
||||
fabRR := Of(func(x int) string {
|
||||
return "value"
|
||||
})
|
||||
result := applyTo42(fabRR)(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestChainOptionK tests the ChainOptionK function
|
||||
func TestChainOptionK(t *testing.T) {
|
||||
t.Run("ChainOptionK returns Right when Option is Some", func(t *testing.T) {
|
||||
chainOpt := ChainOptionK[int, string](func() error {
|
||||
return errors.New("value not found")
|
||||
})
|
||||
optKleisli := func(x int) option.Option[string] {
|
||||
if x > 0 {
|
||||
return option.Some("value")
|
||||
}
|
||||
return option.None[string]()
|
||||
}
|
||||
operator := chainOpt(optKleisli)
|
||||
result := operator(Of(42))(t.Context())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("ChainOptionK returns Left when Option is None", func(t *testing.T) {
|
||||
chainOpt := ChainOptionK[int, string](func() error {
|
||||
return errors.New("value not found")
|
||||
})
|
||||
optKleisli := func(x int) option.Option[string] {
|
||||
return option.None[string]()
|
||||
}
|
||||
operator := chainOpt(optKleisli)
|
||||
result := operator(Of(42))(t.Context())
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ import (
|
||||
//
|
||||
// Example - Context cancellation:
|
||||
//
|
||||
// ctx, cancel := context.WithCancel(context.Background())
|
||||
// ctx, cancel := context.WithCancel(t.Context())
|
||||
// cancel() // Cancel immediately
|
||||
//
|
||||
// computation := TailRec(someStep)
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestTailRecFactorial(t *testing.T) {
|
||||
}
|
||||
|
||||
factorial := TailRec(factorialStep)
|
||||
result := factorial(State{5, 1})(context.Background())
|
||||
result := factorial(State{5, 1})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(120), result)
|
||||
}
|
||||
@@ -68,7 +68,7 @@ func TestTailRecFibonacci(t *testing.T) {
|
||||
}
|
||||
|
||||
fib := TailRec(fibStep)
|
||||
result := fib(State{10, 0, 1})(context.Background())
|
||||
result := fib(State{10, 0, 1})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(89), result) // 10th Fibonacci number
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func TestTailRecCountdown(t *testing.T) {
|
||||
}
|
||||
|
||||
countdown := TailRec(countdownStep)
|
||||
result := countdown(10)(context.Background())
|
||||
result := countdown(10)(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(0), result)
|
||||
}
|
||||
@@ -99,7 +99,7 @@ func TestTailRecImmediateTermination(t *testing.T) {
|
||||
}
|
||||
|
||||
immediate := TailRec(immediateStep)
|
||||
result := immediate(42)(context.Background())
|
||||
result := immediate(42)(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(84), result)
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestTailRecStackSafety(t *testing.T) {
|
||||
}
|
||||
|
||||
countdown := TailRec(countdownStep)
|
||||
result := countdown(10000)(context.Background())
|
||||
result := countdown(10000)(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(0), result)
|
||||
}
|
||||
@@ -138,7 +138,7 @@ func TestTailRecSumList(t *testing.T) {
|
||||
}
|
||||
|
||||
sumList := TailRec(sumStep)
|
||||
result := sumList(State{[]int{1, 2, 3, 4, 5}, 0})(context.Background())
|
||||
result := sumList(State{[]int{1, 2, 3, 4, 5}, 0})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(15), result)
|
||||
}
|
||||
@@ -158,7 +158,7 @@ func TestTailRecCollatzConjecture(t *testing.T) {
|
||||
}
|
||||
|
||||
collatz := TailRec(collatzStep)
|
||||
result := collatz(10)(context.Background())
|
||||
result := collatz(10)(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(1), result)
|
||||
}
|
||||
@@ -180,7 +180,7 @@ func TestTailRecGCD(t *testing.T) {
|
||||
}
|
||||
|
||||
gcd := TailRec(gcdStep)
|
||||
result := gcd(State{48, 18})(context.Background())
|
||||
result := gcd(State{48, 18})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(6), result)
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func TestTailRecErrorPropagation(t *testing.T) {
|
||||
}
|
||||
|
||||
computation := TailRec(errorStep)
|
||||
result := computation(10)(context.Background())
|
||||
result := computation(10)(t.Context())
|
||||
|
||||
assert.True(t, R.IsLeft(result))
|
||||
_, err := R.Unwrap(result)
|
||||
@@ -211,7 +211,7 @@ func TestTailRecErrorPropagation(t *testing.T) {
|
||||
|
||||
// TestTailRecContextCancellationImmediate tests short circuit when context is already canceled
|
||||
func TestTailRecContextCancellationImmediate(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel() // Cancel immediately before execution
|
||||
|
||||
stepExecuted := false
|
||||
@@ -237,7 +237,7 @@ func TestTailRecContextCancellationImmediate(t *testing.T) {
|
||||
|
||||
// TestTailRecContextCancellationDuringExecution tests short circuit when context is canceled during execution
|
||||
func TestTailRecContextCancellationDuringExecution(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
|
||||
executionCount := 0
|
||||
countdownStep := func(n int) ReaderResult[TR.Trampoline[int, int]] {
|
||||
@@ -266,7 +266,7 @@ func TestTailRecContextCancellationDuringExecution(t *testing.T) {
|
||||
|
||||
// TestTailRecContextWithTimeout tests behavior with timeout context
|
||||
func TestTailRecContextWithTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
executionCount := 0
|
||||
@@ -295,7 +295,7 @@ func TestTailRecContextWithTimeout(t *testing.T) {
|
||||
// TestTailRecContextWithCause tests that context.Cause is properly returned
|
||||
func TestTailRecContextWithCause(t *testing.T) {
|
||||
customErr := errors.New("custom cancellation reason")
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
ctx, cancel := context.WithCancelCause(t.Context())
|
||||
cancel(customErr)
|
||||
|
||||
countdownStep := func(n int) ReaderResult[TR.Trampoline[int, int]] {
|
||||
@@ -317,7 +317,7 @@ func TestTailRecContextWithCause(t *testing.T) {
|
||||
|
||||
// TestTailRecContextCancellationMultipleIterations tests that cancellation is checked on each iteration
|
||||
func TestTailRecContextCancellationMultipleIterations(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
|
||||
executionCount := 0
|
||||
maxExecutions := 5
|
||||
@@ -348,7 +348,7 @@ func TestTailRecContextCancellationMultipleIterations(t *testing.T) {
|
||||
|
||||
// TestTailRecContextNotCanceled tests normal execution when context is not canceled
|
||||
func TestTailRecContextNotCanceled(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx := t.Context()
|
||||
|
||||
executionCount := 0
|
||||
countdownStep := func(n int) ReaderResult[TR.Trampoline[int, int]] {
|
||||
@@ -386,7 +386,7 @@ func TestTailRecPowerOfTwo(t *testing.T) {
|
||||
}
|
||||
|
||||
power := TailRec(powerStep)
|
||||
result := power(State{0, 1, 10})(context.Background())
|
||||
result := power(State{0, 1, 10})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(1024), result) // 2^10
|
||||
}
|
||||
@@ -412,7 +412,7 @@ func TestTailRecFindInRange(t *testing.T) {
|
||||
}
|
||||
|
||||
find := TailRec(findStep)
|
||||
result := find(State{0, 100, 42})(context.Background())
|
||||
result := find(State{0, 100, 42})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(42), result)
|
||||
}
|
||||
@@ -438,7 +438,7 @@ func TestTailRecFindNotInRange(t *testing.T) {
|
||||
}
|
||||
|
||||
find := TailRec(findStep)
|
||||
result := find(State{0, 100, 200})(context.Background())
|
||||
result := find(State{0, 100, 200})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of(-1), result)
|
||||
}
|
||||
@@ -448,7 +448,7 @@ func TestTailRecWithContextValue(t *testing.T) {
|
||||
type contextKey string
|
||||
const multiplierKey contextKey = "multiplier"
|
||||
|
||||
ctx := context.WithValue(context.Background(), multiplierKey, 3)
|
||||
ctx := context.WithValue(t.Context(), multiplierKey, 3)
|
||||
|
||||
countdownStep := func(n int) ReaderResult[TR.Trampoline[int, int]] {
|
||||
return func(ctx context.Context) Result[TR.Trampoline[int, int]] {
|
||||
@@ -492,7 +492,7 @@ func TestTailRecComplexState(t *testing.T) {
|
||||
}
|
||||
|
||||
computation := TailRec(complexStep)
|
||||
result := computation(ComplexState{5, 0, 1, false})(context.Background())
|
||||
result := computation(ComplexState{5, 0, 1, false})(t.Context())
|
||||
|
||||
assert.Equal(t, R.Of("sum=15, product=120"), result)
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ import (
|
||||
// retryingFetch := Retrying(policy, fetchData, shouldRetry)
|
||||
//
|
||||
// // Execute with a cancellable context
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
// ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
// defer cancel()
|
||||
// finalResult := retryingFetch(ctx)
|
||||
//
|
||||
|
||||
@@ -20,20 +20,201 @@ import (
|
||||
"github.com/IBM/fp-go/v2/tuple"
|
||||
)
|
||||
|
||||
// SequenceT converts n inputs of higher kinded types into a higher kinded types of n strongly typed values, represented as a tuple
|
||||
// SequenceT functions convert multiple ReaderResult values into a single ReaderResult containing a tuple.
|
||||
// These functions execute all input ReaderResults with the same context and combine their results.
|
||||
//
|
||||
// IMPORTANT: All ReaderResults are executed, even if one fails. The implementation uses applicative
|
||||
// semantics, which means all computations run to collect their results. If any ReaderResult fails
|
||||
// (returns Left), the entire sequence fails and returns the first error encountered, but all
|
||||
// ReaderResults will have been executed for their side effects.
|
||||
//
|
||||
// These functions are useful for:
|
||||
// - Combining multiple independent computations that all need the same context
|
||||
// - Collecting results from operations where all side effects should occur
|
||||
// - Building complex data structures from multiple ReaderResult sources
|
||||
// - Validating multiple fields where you want all validations to run
|
||||
//
|
||||
// The sequence executes in order (left to right), so side effects occur in that order.
|
||||
|
||||
// SequenceT1 converts a single ReaderResult into a ReaderResult containing a 1-tuple.
|
||||
// This is primarily useful for consistency in generic code or when you need to wrap
|
||||
// a single value in a tuple structure.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the value in the ReaderResult
|
||||
//
|
||||
// Parameters:
|
||||
// - a: The ReaderResult to wrap in a tuple
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult containing a Tuple1 with the value from the input
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// rr := readerresult.Of(42)
|
||||
// tupled := readerresult.SequenceT1(rr)
|
||||
// result := tupled(context.Background())
|
||||
// // result is Right(Tuple1{F1: 42})
|
||||
//
|
||||
//go:inline
|
||||
func SequenceT1[A any](a ReaderResult[A]) ReaderResult[tuple.Tuple1[A]] {
|
||||
return readereither.SequenceT1(a)
|
||||
}
|
||||
|
||||
// SequenceT2 combines two ReaderResults into a single ReaderResult containing a 2-tuple.
|
||||
// Both ReaderResults are executed with the same context. If either fails, the entire
|
||||
// sequence fails.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the first value
|
||||
// - B: The type of the second value
|
||||
//
|
||||
// Parameters:
|
||||
// - a: The first ReaderResult
|
||||
// - b: The second ReaderResult
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult containing a Tuple2 with both values
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// getName := readerresult.Of("Alice")
|
||||
// getAge := readerresult.Of(30)
|
||||
// combined := readerresult.SequenceT2(getName, getAge)
|
||||
// result := combined(context.Background())
|
||||
// // result is Right(Tuple2{F1: "Alice", F2: 30})
|
||||
//
|
||||
// Example with error:
|
||||
//
|
||||
// getName := readerresult.Of("Alice")
|
||||
// getAge := readerresult.Left[int](errors.New("age not found"))
|
||||
// combined := readerresult.SequenceT2(getName, getAge)
|
||||
// result := combined(context.Background())
|
||||
// // result is Left(error("age not found"))
|
||||
//
|
||||
//go:inline
|
||||
func SequenceT2[A, B any](a ReaderResult[A], b ReaderResult[B]) ReaderResult[tuple.Tuple2[A, B]] {
|
||||
return readereither.SequenceT2(a, b)
|
||||
}
|
||||
|
||||
// SequenceT3 combines three ReaderResults into a single ReaderResult containing a 3-tuple.
|
||||
// All ReaderResults are executed sequentially with the same context. If any fails,
|
||||
// the entire sequence fails immediately.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the first value
|
||||
// - B: The type of the second value
|
||||
// - C: The type of the third value
|
||||
//
|
||||
// Parameters:
|
||||
// - a: The first ReaderResult
|
||||
// - b: The second ReaderResult
|
||||
// - c: The third ReaderResult
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult containing a Tuple3 with all three values
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// getUserID := readerresult.Of(123)
|
||||
// getUserName := readerresult.Of("Alice")
|
||||
// getUserEmail := readerresult.Of("alice@example.com")
|
||||
// combined := readerresult.SequenceT3(getUserID, getUserName, getUserEmail)
|
||||
// result := combined(context.Background())
|
||||
// // result is Right(Tuple3{F1: 123, F2: "Alice", F3: "alice@example.com"})
|
||||
//
|
||||
// Example with context-aware operations:
|
||||
//
|
||||
// fetchUser := func(ctx context.Context) result.Result[string] {
|
||||
// if ctx.Err() != nil {
|
||||
// return result.Error[string](ctx.Err())
|
||||
// }
|
||||
// return result.Of("Alice")
|
||||
// }
|
||||
// fetchAge := func(ctx context.Context) result.Result[int] {
|
||||
// return result.Of(30)
|
||||
// }
|
||||
// fetchCity := func(ctx context.Context) result.Result[string] {
|
||||
// return result.Of("NYC")
|
||||
// }
|
||||
// combined := readerresult.SequenceT3(fetchUser, fetchAge, fetchCity)
|
||||
// result := combined(context.Background())
|
||||
// // result is Right(Tuple3{F1: "Alice", F2: 30, F3: "NYC"})
|
||||
//
|
||||
//go:inline
|
||||
func SequenceT3[A, B, C any](a ReaderResult[A], b ReaderResult[B], c ReaderResult[C]) ReaderResult[tuple.Tuple3[A, B, C]] {
|
||||
return readereither.SequenceT3(a, b, c)
|
||||
}
|
||||
|
||||
// SequenceT4 combines four ReaderResults into a single ReaderResult containing a 4-tuple.
|
||||
// All ReaderResults are executed sequentially with the same context. If any fails,
|
||||
// the entire sequence fails immediately without executing the remaining ones.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the first value
|
||||
// - B: The type of the second value
|
||||
// - C: The type of the third value
|
||||
// - D: The type of the fourth value
|
||||
//
|
||||
// Parameters:
|
||||
// - a: The first ReaderResult
|
||||
// - b: The second ReaderResult
|
||||
// - c: The third ReaderResult
|
||||
// - d: The fourth ReaderResult
|
||||
//
|
||||
// Returns:
|
||||
// - A ReaderResult containing a Tuple4 with all four values
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// getID := readerresult.Of(123)
|
||||
// getName := readerresult.Of("Alice")
|
||||
// getEmail := readerresult.Of("alice@example.com")
|
||||
// getAge := readerresult.Of(30)
|
||||
// combined := readerresult.SequenceT4(getID, getName, getEmail, getAge)
|
||||
// result := combined(context.Background())
|
||||
// // result is Right(Tuple4{F1: 123, F2: "Alice", F3: "alice@example.com", F4: 30})
|
||||
//
|
||||
// Example with early failure:
|
||||
//
|
||||
// getID := readerresult.Of(123)
|
||||
// getName := readerresult.Left[string](errors.New("name not found"))
|
||||
// getEmail := readerresult.Of("alice@example.com") // Not executed
|
||||
// getAge := readerresult.Of(30) // Not executed
|
||||
// combined := readerresult.SequenceT4(getID, getName, getEmail, getAge)
|
||||
// result := combined(context.Background())
|
||||
// // result is Left(error("name not found"))
|
||||
// // getEmail and getAge are never executed due to early failure
|
||||
//
|
||||
// Example building a complex structure:
|
||||
//
|
||||
// type UserProfile struct {
|
||||
// ID int
|
||||
// Name string
|
||||
// Email string
|
||||
// Age int
|
||||
// }
|
||||
//
|
||||
// fetchUserData := readerresult.SequenceT4(
|
||||
// fetchUserID(userID),
|
||||
// fetchUserName(userID),
|
||||
// fetchUserEmail(userID),
|
||||
// fetchUserAge(userID),
|
||||
// )
|
||||
//
|
||||
// buildProfile := readerresult.Map(func(t tuple.Tuple4[int, string, string, int]) UserProfile {
|
||||
// return UserProfile{
|
||||
// ID: t.F1,
|
||||
// Name: t.F2,
|
||||
// Email: t.F3,
|
||||
// Age: t.F4,
|
||||
// }
|
||||
// })
|
||||
//
|
||||
// userProfile := F.Pipe1(fetchUserData, buildProfile)
|
||||
// result := userProfile(context.Background())
|
||||
//
|
||||
//go:inline
|
||||
func SequenceT4[A, B, C, D any](a ReaderResult[A], b ReaderResult[B], c ReaderResult[C], d ReaderResult[D]) ReaderResult[tuple.Tuple4[A, B, C, D]] {
|
||||
return readereither.SequenceT4(a, b, c, d)
|
||||
}
|
||||
|
||||
460
v2/context/readerresult/sequence_test.go
Normal file
460
v2/context/readerresult/sequence_test.go
Normal file
@@ -0,0 +1,460 @@
|
||||
// Copyright (c) 2023 - 2025 IBM Corp.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package readerresult
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
E "github.com/IBM/fp-go/v2/either"
|
||||
"github.com/IBM/fp-go/v2/tuple"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestSequenceT1 tests the SequenceT1 function
|
||||
func TestSequenceT1(t *testing.T) {
|
||||
t.Run("wraps single success value in tuple", func(t *testing.T) {
|
||||
rr := Of(42)
|
||||
tupled := SequenceT1(rr)
|
||||
result := tupled(context.Background())
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 42, val.F1)
|
||||
})
|
||||
|
||||
t.Run("preserves error", func(t *testing.T) {
|
||||
testErr := errors.New("test error")
|
||||
rr := Left[int](testErr)
|
||||
tupled := SequenceT1(rr)
|
||||
result := tupled(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
rr := func(ctx context.Context) E.Either[error, int] {
|
||||
if ctx.Err() != nil {
|
||||
return E.Left[int](ctx.Err())
|
||||
}
|
||||
return E.Of[error](42)
|
||||
}
|
||||
|
||||
tupled := SequenceT1(rr)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := tupled(ctx)
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestSequenceT2 tests the SequenceT2 function
|
||||
func TestSequenceT2(t *testing.T) {
|
||||
t.Run("combines two success values into tuple", func(t *testing.T) {
|
||||
getName := Of("Alice")
|
||||
getAge := Of(30)
|
||||
|
||||
combined := SequenceT2(getName, getAge)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, "Alice", val.F1)
|
||||
assert.Equal(t, 30, val.F2)
|
||||
})
|
||||
|
||||
t.Run("fails if first ReaderResult fails", func(t *testing.T) {
|
||||
testErr := errors.New("name not found")
|
||||
getName := Left[string](testErr)
|
||||
getAge := Of(30)
|
||||
|
||||
combined := SequenceT2(getName, getAge)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("fails if second ReaderResult fails", func(t *testing.T) {
|
||||
testErr := errors.New("age not found")
|
||||
getName := Of("Alice")
|
||||
getAge := Left[int](testErr)
|
||||
|
||||
combined := SequenceT2(getName, getAge)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("executes both ReaderResults with same context", func(t *testing.T) {
|
||||
type ctxKey string
|
||||
ctx := context.WithValue(context.Background(), ctxKey("key"), "shared")
|
||||
|
||||
getName := func(ctx context.Context) E.Either[error, string] {
|
||||
val := ctx.Value(ctxKey("key"))
|
||||
if val != nil {
|
||||
return E.Of[error](val.(string))
|
||||
}
|
||||
return E.Left[string](errors.New("key not found"))
|
||||
}
|
||||
|
||||
getAge := func(ctx context.Context) E.Either[error, int] {
|
||||
val := ctx.Value(ctxKey("key"))
|
||||
if val != nil {
|
||||
return E.Of[error](len(val.(string)))
|
||||
}
|
||||
return E.Left[int](errors.New("key not found"))
|
||||
}
|
||||
|
||||
combined := SequenceT2(getName, getAge)
|
||||
result := combined(ctx)
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, "shared", val.F1)
|
||||
assert.Equal(t, 6, val.F2) // len("shared")
|
||||
})
|
||||
|
||||
t.Run("executes all ReaderResults even if one fails", func(t *testing.T) {
|
||||
firstExecuted := false
|
||||
secondExecuted := false
|
||||
|
||||
first := func(ctx context.Context) E.Either[error, int] {
|
||||
firstExecuted = true
|
||||
return E.Left[int](errors.New("first failed"))
|
||||
}
|
||||
|
||||
second := func(ctx context.Context) E.Either[error, string] {
|
||||
secondExecuted = true
|
||||
return E.Of[error]("second")
|
||||
}
|
||||
|
||||
combined := SequenceT2(first, second)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, firstExecuted, "first should be executed")
|
||||
assert.True(t, secondExecuted, "second should be executed (applicative semantics)")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestSequenceT3 tests the SequenceT3 function
|
||||
func TestSequenceT3(t *testing.T) {
|
||||
t.Run("combines three success values into tuple", func(t *testing.T) {
|
||||
getUserID := Of(123)
|
||||
getUserName := Of("Alice")
|
||||
getUserEmail := Of("alice@example.com")
|
||||
|
||||
combined := SequenceT3(getUserID, getUserName, getUserEmail)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 123, val.F1)
|
||||
assert.Equal(t, "Alice", val.F2)
|
||||
assert.Equal(t, "alice@example.com", val.F3)
|
||||
})
|
||||
|
||||
t.Run("fails if any ReaderResult fails", func(t *testing.T) {
|
||||
testErr := errors.New("email not found")
|
||||
getUserID := Of(123)
|
||||
getUserName := Of("Alice")
|
||||
getUserEmail := Left[string](testErr)
|
||||
|
||||
combined := SequenceT3(getUserID, getUserName, getUserEmail)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("executes all ReaderResults even if one fails", func(t *testing.T) {
|
||||
firstExecuted := false
|
||||
secondExecuted := false
|
||||
thirdExecuted := false
|
||||
|
||||
first := func(ctx context.Context) E.Either[error, int] {
|
||||
firstExecuted = true
|
||||
return E.Of[error](1)
|
||||
}
|
||||
|
||||
second := func(ctx context.Context) E.Either[error, int] {
|
||||
secondExecuted = true
|
||||
return E.Left[int](errors.New("second failed"))
|
||||
}
|
||||
|
||||
third := func(ctx context.Context) E.Either[error, int] {
|
||||
thirdExecuted = true
|
||||
return E.Of[error](3)
|
||||
}
|
||||
|
||||
combined := SequenceT3(first, second, third)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, firstExecuted, "first should be executed")
|
||||
assert.True(t, secondExecuted, "second should be executed")
|
||||
assert.True(t, thirdExecuted, "third should be executed (applicative semantics)")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("respects context cancellation", func(t *testing.T) {
|
||||
getUserID := func(ctx context.Context) E.Either[error, int] {
|
||||
if ctx.Err() != nil {
|
||||
return E.Left[int](ctx.Err())
|
||||
}
|
||||
return E.Of[error](123)
|
||||
}
|
||||
|
||||
getUserName := Of("Alice")
|
||||
getUserEmail := Of("alice@example.com")
|
||||
|
||||
combined := SequenceT3(getUserID, getUserName, getUserEmail)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
result := combined(ctx)
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
}
|
||||
|
||||
// TestSequenceT4 tests the SequenceT4 function
|
||||
func TestSequenceT4(t *testing.T) {
|
||||
t.Run("combines four success values into tuple", func(t *testing.T) {
|
||||
getID := Of(123)
|
||||
getName := Of("Alice")
|
||||
getEmail := Of("alice@example.com")
|
||||
getAge := Of(30)
|
||||
|
||||
combined := SequenceT4(getID, getName, getEmail, getAge)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 123, val.F1)
|
||||
assert.Equal(t, "Alice", val.F2)
|
||||
assert.Equal(t, "alice@example.com", val.F3)
|
||||
assert.Equal(t, 30, val.F4)
|
||||
})
|
||||
|
||||
t.Run("fails if any ReaderResult fails", func(t *testing.T) {
|
||||
testErr := errors.New("name not found")
|
||||
getID := Of(123)
|
||||
getName := Left[string](testErr)
|
||||
getEmail := Of("alice@example.com")
|
||||
getAge := Of(30)
|
||||
|
||||
combined := SequenceT4(getID, getName, getEmail, getAge)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
_, err := E.UnwrapError(result)
|
||||
assert.Equal(t, testErr, err)
|
||||
})
|
||||
|
||||
t.Run("executes all ReaderResults even if one fails", func(t *testing.T) {
|
||||
firstExecuted := false
|
||||
secondExecuted := false
|
||||
thirdExecuted := false
|
||||
fourthExecuted := false
|
||||
|
||||
first := func(ctx context.Context) E.Either[error, int] {
|
||||
firstExecuted = true
|
||||
return E.Of[error](1)
|
||||
}
|
||||
|
||||
second := func(ctx context.Context) E.Either[error, int] {
|
||||
secondExecuted = true
|
||||
return E.Left[int](errors.New("second failed"))
|
||||
}
|
||||
|
||||
third := func(ctx context.Context) E.Either[error, int] {
|
||||
thirdExecuted = true
|
||||
return E.Of[error](3)
|
||||
}
|
||||
|
||||
fourth := func(ctx context.Context) E.Either[error, int] {
|
||||
fourthExecuted = true
|
||||
return E.Of[error](4)
|
||||
}
|
||||
|
||||
combined := SequenceT4(first, second, third, fourth)
|
||||
result := combined(context.Background())
|
||||
|
||||
assert.True(t, firstExecuted, "first should be executed")
|
||||
assert.True(t, secondExecuted, "second should be executed")
|
||||
assert.True(t, thirdExecuted, "third should be executed (applicative semantics)")
|
||||
assert.True(t, fourthExecuted, "fourth should be executed (applicative semantics)")
|
||||
assert.True(t, E.IsLeft(result))
|
||||
})
|
||||
|
||||
t.Run("can be used to build complex structures", func(t *testing.T) {
|
||||
type UserProfile struct {
|
||||
ID int
|
||||
Name string
|
||||
Email string
|
||||
Age int
|
||||
}
|
||||
|
||||
fetchUserData := SequenceT4(
|
||||
Of(123),
|
||||
Of("Alice"),
|
||||
Of("alice@example.com"),
|
||||
Of(30),
|
||||
)
|
||||
|
||||
buildProfile := Map(func(t tuple.Tuple4[int, string, string, int]) UserProfile {
|
||||
return UserProfile{
|
||||
ID: t.F1,
|
||||
Name: t.F2,
|
||||
Email: t.F3,
|
||||
Age: t.F4,
|
||||
}
|
||||
})
|
||||
|
||||
userProfile := func(ctx context.Context) E.Either[error, UserProfile] {
|
||||
tupleResult := fetchUserData(ctx)
|
||||
if E.IsLeft(tupleResult) {
|
||||
_, err := E.UnwrapError(tupleResult)
|
||||
return E.Left[UserProfile](err)
|
||||
}
|
||||
tupleVal, _ := E.Unwrap(tupleResult)
|
||||
return buildProfile(Of(tupleVal))(ctx)
|
||||
}
|
||||
|
||||
result := userProfile(context.Background())
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
profile, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 123, profile.ID)
|
||||
assert.Equal(t, "Alice", profile.Name)
|
||||
assert.Equal(t, "alice@example.com", profile.Email)
|
||||
assert.Equal(t, 30, profile.Age)
|
||||
})
|
||||
|
||||
t.Run("executes all with same context", func(t *testing.T) {
|
||||
type ctxKey string
|
||||
ctx := context.WithValue(context.Background(), ctxKey("multiplier"), 2)
|
||||
|
||||
getBase := func(ctx context.Context) E.Either[error, int] {
|
||||
return E.Of[error](10)
|
||||
}
|
||||
|
||||
multiply := func(ctx context.Context) E.Either[error, int] {
|
||||
mult := ctx.Value(ctxKey("multiplier")).(int)
|
||||
return E.Of[error](mult)
|
||||
}
|
||||
|
||||
getResult := func(ctx context.Context) E.Either[error, int] {
|
||||
mult := ctx.Value(ctxKey("multiplier")).(int)
|
||||
return E.Of[error](10 * mult)
|
||||
}
|
||||
|
||||
getDescription := func(ctx context.Context) E.Either[error, string] {
|
||||
return E.Of[error]("calculated")
|
||||
}
|
||||
|
||||
combined := SequenceT4(getBase, multiply, getResult, getDescription)
|
||||
result := combined(ctx)
|
||||
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 10, val.F1)
|
||||
assert.Equal(t, 2, val.F2)
|
||||
assert.Equal(t, 20, val.F3)
|
||||
assert.Equal(t, "calculated", val.F4)
|
||||
})
|
||||
}
|
||||
|
||||
// TestSequenceIntegration tests integration scenarios
|
||||
func TestSequenceIntegration(t *testing.T) {
|
||||
t.Run("SequenceT2 with Map to transform tuple", func(t *testing.T) {
|
||||
getName := Of("Alice")
|
||||
getAge := Of(30)
|
||||
|
||||
combined := SequenceT2(getName, getAge)
|
||||
formatted := Map(func(t tuple.Tuple2[string, int]) string {
|
||||
return t.F1 + " is " + string(rune(t.F2+48)) + " years old"
|
||||
})
|
||||
|
||||
pipeline := func(ctx context.Context) E.Either[error, string] {
|
||||
tupleResult := combined(ctx)
|
||||
if E.IsLeft(tupleResult) {
|
||||
_, err := E.UnwrapError(tupleResult)
|
||||
return E.Left[string](err)
|
||||
}
|
||||
tupleVal, _ := E.Unwrap(tupleResult)
|
||||
return formatted(Of(tupleVal))(ctx)
|
||||
}
|
||||
|
||||
result := pipeline(context.Background())
|
||||
assert.True(t, E.IsRight(result))
|
||||
})
|
||||
|
||||
t.Run("SequenceT3 with Chain for dependent operations", func(t *testing.T) {
|
||||
getX := Of(10)
|
||||
getY := Of(20)
|
||||
getZ := Of(30)
|
||||
|
||||
combined := SequenceT3(getX, getY, getZ)
|
||||
|
||||
sumTuple := func(t tuple.Tuple3[int, int, int]) ReaderResult[int] {
|
||||
return Of(t.F1 + t.F2 + t.F3)
|
||||
}
|
||||
|
||||
pipeline := func(ctx context.Context) E.Either[error, int] {
|
||||
tupleResult := combined(ctx)
|
||||
if E.IsLeft(tupleResult) {
|
||||
_, err := E.UnwrapError(tupleResult)
|
||||
return E.Left[int](err)
|
||||
}
|
||||
tupleVal, _ := E.Unwrap(tupleResult)
|
||||
return sumTuple(tupleVal)(ctx)
|
||||
}
|
||||
|
||||
result := pipeline(context.Background())
|
||||
assert.True(t, E.IsRight(result))
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 60, val) // 10 + 20 + 30
|
||||
})
|
||||
|
||||
t.Run("nested sequences", func(t *testing.T) {
|
||||
// Create two pairs
|
||||
pair1 := SequenceT2(Of(1), Of(2))
|
||||
pair2 := SequenceT2(Of(3), Of(4))
|
||||
|
||||
// Combine the pairs
|
||||
combined := SequenceT2(pair1, pair2)
|
||||
|
||||
result := combined(context.Background())
|
||||
assert.True(t, E.IsRight(result))
|
||||
|
||||
val, _ := E.Unwrap(result)
|
||||
assert.Equal(t, 1, val.F1.F1)
|
||||
assert.Equal(t, 2, val.F1.F2)
|
||||
assert.Equal(t, 3, val.F2.F1)
|
||||
assert.Equal(t, 4, val.F2.F2)
|
||||
})
|
||||
}
|
||||
@@ -15,6 +15,38 @@
|
||||
|
||||
// Package readerresult implements a specialization of the Reader monad assuming a golang context as the context of the monad and a standard golang error.
|
||||
//
|
||||
// # Side Effects and Context
|
||||
//
|
||||
// IMPORTANT: In contrast to the functional readerresult package (readerresult.ReaderResult[R, A]),
|
||||
// this context/readerresult package has side effects by design because it depends on context.Context,
|
||||
// which is inherently effectful:
|
||||
// - context.Context can be cancelled (ctx.Done() channel)
|
||||
// - context.Context has deadlines and timeouts (ctx.Deadline())
|
||||
// - context.Context carries request-scoped values (ctx.Value())
|
||||
// - context.Context propagates cancellation signals across goroutines
|
||||
//
|
||||
// This means that ReaderResult[A] = func(context.Context) (A, error) represents an EFFECTFUL computation,
|
||||
// not a pure function. The computation's behavior can change based on the context's state (cancelled,
|
||||
// timed out, etc.), making it fundamentally different from a pure Reader monad.
|
||||
//
|
||||
// Comparison of packages:
|
||||
// - readerresult.ReaderResult[R, A] = func(R) Result[A] - PURE (R can be any type, no side effects)
|
||||
// - idiomatic/readerresult.ReaderResult[R, A] = func(R) (A, error) - EFFECTFUL (also uses context.Context)
|
||||
// - context/readerresult.ReaderResult[A] = func(context.Context) (A, error) - EFFECTFUL (uses context.Context)
|
||||
//
|
||||
// Use this package (context/readerresult) when you need:
|
||||
// - Cancellation support for long-running operations
|
||||
// - Timeout/deadline handling
|
||||
// - Request-scoped values (tracing IDs, user context, etc.)
|
||||
// - Integration with Go's standard context-aware APIs
|
||||
// - Idiomatic Go error handling with (value, error) tuples
|
||||
//
|
||||
// Use the functional readerresult package when you need:
|
||||
// - Pure dependency injection without side effects
|
||||
// - Testable computations with simple state/config objects
|
||||
// - Functional composition without context propagation
|
||||
// - Generic environment types (not limited to context.Context)
|
||||
//
|
||||
// # Pure vs Effectful Functions
|
||||
//
|
||||
// This package distinguishes between pure (side-effect free) and effectful (side-effectful) functions:
|
||||
@@ -45,6 +77,8 @@ import (
|
||||
|
||||
"github.com/IBM/fp-go/v2/either"
|
||||
"github.com/IBM/fp-go/v2/endomorphism"
|
||||
"github.com/IBM/fp-go/v2/io"
|
||||
"github.com/IBM/fp-go/v2/ioresult"
|
||||
"github.com/IBM/fp-go/v2/optics/lens"
|
||||
"github.com/IBM/fp-go/v2/optics/prism"
|
||||
"github.com/IBM/fp-go/v2/option"
|
||||
@@ -56,18 +90,245 @@ import (
|
||||
)
|
||||
|
||||
type (
|
||||
Option[A any] = option.Option[A]
|
||||
Either[A any] = either.Either[error, A]
|
||||
Result[A any] = result.Result[A]
|
||||
// Option represents an optional value that may or may not be present.
|
||||
// This is an alias for option.Option[A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the value that may be present
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// opt := option.Some(42) // Option[int] with value
|
||||
// none := option.None[int]() // Option[int] without value
|
||||
Option[A any] = option.Option[A]
|
||||
|
||||
// Either represents a value that can be either a Left (error) or Right (success).
|
||||
// This is specialized to use error as the Left type.
|
||||
// This is an alias for either.Either[error, A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the Right (success) value
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// success := either.Right[error, int](42) // Right(42)
|
||||
// failure := either.Left[int](errors.New("failed")) // Left(error)
|
||||
Either[A any] = either.Either[error, A]
|
||||
|
||||
// Result represents a computation that can either succeed with a value or fail with an error.
|
||||
// This is an alias for result.Result[A], which is equivalent to Either[error, A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the success value
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// success := result.Of[error](42) // Right(42)
|
||||
// failure := result.Error[int](errors.New("failed")) // Left(error)
|
||||
Result[A any] = result.Result[A]
|
||||
|
||||
// Reader represents a computation that depends on an environment R to produce a value A.
|
||||
// This is an alias for reader.Reader[R, A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - R: The type of the environment/context
|
||||
// - A: The type of the produced value
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// type Config struct { Port int }
|
||||
// getPort := func(cfg Config) int { return cfg.Port }
|
||||
// // getPort is a Reader[Config, int]
|
||||
Reader[R, A any] = reader.Reader[R, A]
|
||||
// ReaderResult is a specialization of the Reader monad for the typical golang scenario
|
||||
|
||||
// ReaderResult is a specialization of the Reader monad for the typical Go scenario.
|
||||
// It represents an effectful computation that:
|
||||
// - Depends on context.Context (for cancellation, deadlines, values)
|
||||
// - Can fail with an error
|
||||
// - Produces a value of type A on success
|
||||
//
|
||||
// IMPORTANT: This is an EFFECTFUL type because context.Context is effectful.
|
||||
// The computation's behavior can change based on context state (cancelled, timed out, etc.).
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the success value
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type ReaderResult[A any] = func(context.Context) Result[A]
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// getUserByID := func(ctx context.Context) result.Result[User] {
|
||||
// if ctx.Err() != nil {
|
||||
// return result.Error[User](ctx.Err())
|
||||
// }
|
||||
// // Fetch user from database
|
||||
// return result.Of(User{ID: 123, Name: "Alice"})
|
||||
// }
|
||||
// // getUserByID is a ReaderResult[User]
|
||||
ReaderResult[A any] = readereither.ReaderEither[context.Context, error, A]
|
||||
|
||||
Kleisli[A, B any] = reader.Reader[A, ReaderResult[B]]
|
||||
Operator[A, B any] = Kleisli[ReaderResult[A], B]
|
||||
Endomorphism[A any] = endomorphism.Endomorphism[A]
|
||||
Prism[S, T any] = prism.Prism[S, T]
|
||||
Lens[S, T any] = lens.Lens[S, T]
|
||||
// Kleisli represents a function that takes a value of type A and returns a ReaderResult[B].
|
||||
// This is the fundamental building block for composing ReaderResult computations.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The input type
|
||||
// - B: The output type (wrapped in ReaderResult)
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type Kleisli[A, B any] = func(A) ReaderResult[B]
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// getUserByID := func(id int) readerresult.ReaderResult[User] {
|
||||
// return func(ctx context.Context) result.Result[User] {
|
||||
// // Fetch user from database
|
||||
// return result.Of(User{ID: id, Name: "Alice"})
|
||||
// }
|
||||
// }
|
||||
// // getUserByID is a Kleisli[int, User]
|
||||
Kleisli[A, B any] = reader.Reader[A, ReaderResult[B]]
|
||||
|
||||
// Operator represents a function that transforms one ReaderResult into another.
|
||||
// This is a specialized Kleisli where the input is itself a ReaderResult.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The input ReaderResult's success type
|
||||
// - B: The output ReaderResult's success type
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type Operator[A, B any] = func(ReaderResult[A]) ReaderResult[B]
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// mapToString := readerresult.Map(func(x int) string {
|
||||
// return fmt.Sprintf("value: %d", x)
|
||||
// })
|
||||
// // mapToString is an Operator[int, string]
|
||||
Operator[A, B any] = Kleisli[ReaderResult[A], B]
|
||||
|
||||
// Endomorphism represents a function that transforms a value to the same type.
|
||||
// This is an alias for endomorphism.Endomorphism[A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the value
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type Endomorphism[A any] = func(A) A
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// increment := func(x int) int { return x + 1 }
|
||||
// // increment is an Endomorphism[int]
|
||||
Endomorphism[A any] = endomorphism.Endomorphism[A]
|
||||
|
||||
// Prism is an optic that focuses on a part of a data structure that may or may not be present.
|
||||
// This is an alias for prism.Prism[S, T].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - S: The source type
|
||||
// - T: The target type
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // A prism that extracts an int from a string if it's a valid number
|
||||
// intPrism := prism.Prism[string, int]{...}
|
||||
Prism[S, T any] = prism.Prism[S, T]
|
||||
|
||||
// Lens is an optic that focuses on a part of a data structure that is always present.
|
||||
// This is an alias for lens.Lens[S, T].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - S: The source type
|
||||
// - T: The target type
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // A lens that focuses on the Name field of a User
|
||||
// nameLens := lens.Lens[User, string]{...}
|
||||
Lens[S, T any] = lens.Lens[S, T]
|
||||
|
||||
// Trampoline represents a computation that can be executed in a stack-safe manner
|
||||
// using tail recursion elimination. This is an alias for tailrec.Trampoline[A, B].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The input type
|
||||
// - B: The output type
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// // A tail-recursive factorial computation
|
||||
// factorial := tailrec.Trampoline[int, int]{...}
|
||||
Trampoline[A, B any] = tailrec.Trampoline[A, B]
|
||||
Predicate[A any] = predicate.Predicate[A]
|
||||
|
||||
// Predicate represents a function that tests a value and returns a boolean.
|
||||
// This is an alias for predicate.Predicate[A].
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the value to test
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type Predicate[A any] = func(A) bool
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// isPositive := func(x int) bool { return x > 0 }
|
||||
// // isPositive is a Predicate[int]
|
||||
Predicate[A any] = predicate.Predicate[A]
|
||||
|
||||
// IO represents a side-effectful computation that produces a value of type A.
|
||||
// This is an alias for io.IO[A].
|
||||
//
|
||||
// IMPORTANT: IO operations have side effects (file I/O, network calls, etc.).
|
||||
// Combining IO with ReaderResult makes sense because ReaderResult is already effectful
|
||||
// due to its dependency on context.Context.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the value produced by the IO operation
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type IO[A any] = func() A
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// readConfig := func() Config {
|
||||
// // Side effect: read from file
|
||||
// data, _ := os.ReadFile("config.json")
|
||||
// return parseConfig(data)
|
||||
// }
|
||||
// // readConfig is an IO[Config]
|
||||
IO[A any] = io.IO[A]
|
||||
|
||||
// IOResult represents a side-effectful computation that can fail with an error.
|
||||
// This combines IO (side effects) with Result (error handling).
|
||||
// This is an alias for ioresult.IOResult[A].
|
||||
//
|
||||
// IMPORTANT: IOResult operations have side effects and can fail.
|
||||
// Combining IOResult with ReaderResult makes sense because both are effectful.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - A: The type of the success value
|
||||
//
|
||||
// Signature:
|
||||
//
|
||||
// type IOResult[A any] = func() Result[A]
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// readConfig := func() result.Result[Config] {
|
||||
// // Side effect: read from file
|
||||
// data, err := os.ReadFile("config.json")
|
||||
// if err != nil {
|
||||
// return result.Error[Config](err)
|
||||
// }
|
||||
// return result.Of(parseConfig(data))
|
||||
// }
|
||||
// // readConfig is an IOResult[Config]
|
||||
IOResult[A any] = ioresult.IOResult[A]
|
||||
)
|
||||
|
||||
@@ -533,5 +533,3 @@ func BenchmarkExecuteLocal(b *testing.B) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Made with Bob
|
||||
|
||||
@@ -60,3 +60,5 @@ type Apply[A, B, HKTA, HKTB, HKTFAB any] interface {
|
||||
func ToFunctor[A, B, HKTA, HKTB, HKTFAB any](ap Apply[A, B, HKTA, HKTB, HKTFAB]) functor.Functor[A, B, HKTA, HKTB] {
|
||||
return ap
|
||||
}
|
||||
|
||||
type ApType[HKTA, HKTB, HKTFAB any] = func(HKTA) func(HKTFAB) HKTB
|
||||
|
||||
@@ -47,3 +47,5 @@ type Functor[A, B, HKTA, HKTB any] interface {
|
||||
// Returns a function that takes a functor containing A and returns a functor containing B.
|
||||
Map(func(A) B) func(HKTA) HKTB
|
||||
}
|
||||
|
||||
type MapType[A, B, HKTA, HKTB any] = func(func(A) B) func(HKTA) HKTB
|
||||
|
||||
@@ -37,3 +37,5 @@ type Pointed[A, HKTA any] interface {
|
||||
// creating a valid instance of the higher-kinded type.
|
||||
Of(A) HKTA
|
||||
}
|
||||
|
||||
type OfType[A, HKTA any] = func(A) HKTA
|
||||
|
||||
119
v2/internal/traversable/types.go
Normal file
119
v2/internal/traversable/types.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package traversable
|
||||
|
||||
import (
|
||||
F "github.com/IBM/fp-go/v2/function"
|
||||
"github.com/IBM/fp-go/v2/internal/applicative"
|
||||
"github.com/IBM/fp-go/v2/internal/apply"
|
||||
"github.com/IBM/fp-go/v2/internal/functor"
|
||||
"github.com/IBM/fp-go/v2/internal/pointed"
|
||||
)
|
||||
|
||||
type (
|
||||
Pointed[A, HKT_A any] = pointed.Pointed[A, HKT_A]
|
||||
Functor[A, B, HKT_A, HKT_B any] = functor.Functor[A, B, HKT_A, HKT_B]
|
||||
Applicative[A, B, HKT_A, HKT_B, HKT_AB any] = applicative.Applicative[A, B, HKT_A, HKT_B, HKT_AB]
|
||||
|
||||
TraverseType[A, B, HKT_T_A, HKT_T_B, HKT_F_B, HKT_F_T_B, HKT_F_T_A_B any] = func(
|
||||
// applicative F
|
||||
f_of pointed.OfType[HKT_T_B, HKT_F_T_B],
|
||||
f_map functor.MapType[HKT_T_B, func(B) HKT_T_B, HKT_F_T_B, HKT_F_T_A_B],
|
||||
f_ap apply.ApType[HKT_F_B, HKT_F_T_B, HKT_F_T_A_B],
|
||||
|
||||
) func(func(A) HKT_F_B) func(HKT_T_A) HKT_F_T_B
|
||||
|
||||
SequenceType[
|
||||
HKT_T_F_A,
|
||||
HKT_F_T_A any] = func(
|
||||
// applicative F
|
||||
f_of pointed.OfType[HKT_T_F_A, HKT_F_T_A],
|
||||
f_map functor.MapType[HKT_T_F_A, func(HKT_T_F_A) HKT_T_F_A, HKT_F_T_A, HKT_T_F_A],
|
||||
f_ap apply.ApType[HKT_T_F_A, HKT_F_T_A, HKT_T_F_A],
|
||||
) func(HKT_T_F_A) HKT_F_T_A
|
||||
)
|
||||
|
||||
func ComposeTraverse[
|
||||
A,
|
||||
B,
|
||||
HKT_F_B,
|
||||
HKT_G_A,
|
||||
HKT_G_B,
|
||||
HKT_T_G_A,
|
||||
HKT_T_G_B,
|
||||
HKT_F_G_B,
|
||||
HKT_F_T_G_B,
|
||||
HKT_F_T_A_B any](
|
||||
t TraverseType[HKT_G_A, HKT_G_B, HKT_T_G_A, HKT_T_G_B, HKT_F_G_B, HKT_F_T_G_B, HKT_F_T_A_B],
|
||||
g TraverseType[A, B, HKT_G_A, HKT_G_B, HKT_F_B, HKT_F_G_B, HKT_F_T_A_B],
|
||||
) func(
|
||||
// applicative F
|
||||
f_of pointed.OfType[HKT_T_G_B, HKT_F_T_G_B],
|
||||
f_map functor.MapType[HKT_T_G_B, func(HKT_G_B) HKT_T_G_B, HKT_F_T_G_B, HKT_F_T_A_B],
|
||||
f_ap apply.ApType[HKT_F_G_B, HKT_F_T_G_B, HKT_F_T_A_B],
|
||||
|
||||
// applicative G
|
||||
g_of pointed.OfType[HKT_G_B, HKT_F_G_B],
|
||||
g_map functor.MapType[HKT_G_B, func(B) HKT_G_B, HKT_F_G_B, HKT_F_T_A_B],
|
||||
g_ap apply.ApType[HKT_F_B, HKT_F_G_B, HKT_F_T_A_B],
|
||||
) func(func(A) HKT_F_B) func(HKT_T_G_A) HKT_F_T_G_B {
|
||||
|
||||
return func(
|
||||
// applicative F
|
||||
f_of pointed.OfType[HKT_T_G_B, HKT_F_T_G_B],
|
||||
f_map functor.MapType[HKT_T_G_B, func(HKT_G_B) HKT_T_G_B, HKT_F_T_G_B, HKT_F_T_A_B],
|
||||
f_ap apply.ApType[HKT_F_G_B, HKT_F_T_G_B, HKT_F_T_A_B],
|
||||
|
||||
// applicative G
|
||||
g_of pointed.OfType[HKT_G_B, HKT_F_G_B],
|
||||
g_map functor.MapType[HKT_G_B, func(B) HKT_G_B, HKT_F_G_B, HKT_F_T_A_B],
|
||||
g_ap apply.ApType[HKT_F_B, HKT_F_G_B, HKT_F_T_A_B],
|
||||
|
||||
) func(func(A) HKT_F_B) func(HKT_T_G_A) HKT_F_T_G_B {
|
||||
|
||||
return F.Flow2(
|
||||
g(g_of, g_map, g_ap),
|
||||
t(f_of, f_map, f_ap),
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// func ComposeSequence[
|
||||
// HKT_F_G_A,
|
||||
// HKT_G_F_A,
|
||||
// HKT_T_G_F_A,
|
||||
// HKT_F_T_G_A,
|
||||
// HKT_T_F_G_A any](
|
||||
|
||||
// t SequenceType[HKT_T_F_G_A, HKT_F_T_G_A],
|
||||
// t_map functor.MapType[HKT_G_F_A, HKT_F_G_A, HKT_T_G_F_A, HKT_T_F_G_A],
|
||||
|
||||
// g SequenceType[HKT_G_F_A, HKT_F_G_A],
|
||||
// ) func(
|
||||
// // applicative F
|
||||
// ) func(HKT_T_G_F_A) HKT_F_T_G_A {
|
||||
|
||||
// return func() func(HKT_T_G_F_A) HKT_F_T_G_A {
|
||||
// return F.Flow2(
|
||||
// t_map(g()),
|
||||
// t(),
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
|
||||
func SequenceFromTraverse[
|
||||
A, HKT_T_A, HKT_F_B, HKT_F_T_B any](
|
||||
t TraverseType[HKT_T_A, HKT_T_A, HKT_T_A, HKT_T_A, HKT_T_A, HKT_F_T_B, HKT_T_A],
|
||||
) SequenceType[HKT_T_A, HKT_F_T_B] {
|
||||
|
||||
return func(
|
||||
// applicative F
|
||||
f_of pointed.OfType[HKT_T_A, HKT_F_T_B],
|
||||
f_map functor.MapType[HKT_T_A, func(HKT_T_A) HKT_T_A, HKT_F_T_B, HKT_T_A],
|
||||
f_ap apply.ApType[HKT_T_A, HKT_F_T_B, HKT_T_A],
|
||||
) func(HKT_T_A) HKT_F_T_B {
|
||||
return F.Pipe1(
|
||||
F.Identity[HKT_T_A],
|
||||
t(f_of, f_map, f_ap),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user