mirror of
https://github.com/IBM/fp-go.git
synced 2026-03-10 13:31:01 +02:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb2e0b23e8 |
@@ -52,7 +52,7 @@ import (
|
||||
//
|
||||
// - f: A Kleisli arrow (A => ReaderIOResult[Trampoline[A, B]]) that:
|
||||
// - Takes the current state A
|
||||
// - Returns a ReaderIOResult that depends on [context.Context]
|
||||
// - Returns a ReaderIOResult that depends on context.Context
|
||||
// - Can fail with error (Left in the outer Either)
|
||||
// - Produces Trampoline[A, B] to control recursion flow (Right in the outer Either)
|
||||
//
|
||||
@@ -60,13 +60,13 @@ import (
|
||||
//
|
||||
// A Kleisli arrow (A => ReaderIOResult[B]) that:
|
||||
// - Takes an initial state A
|
||||
// - Returns a ReaderIOResult that requires [context.Context]
|
||||
// - Returns a ReaderIOResult that requires context.Context
|
||||
// - Can fail with error or context cancellation
|
||||
// - Produces the final result B after recursion completes
|
||||
//
|
||||
// # Context Cancellation
|
||||
//
|
||||
// Unlike the base [readerioresult.TailRec], this version automatically integrates
|
||||
// Unlike the base readerioresult.TailRec, this version automatically integrates
|
||||
// context cancellation checking:
|
||||
// - Each recursive iteration checks if the context is cancelled
|
||||
// - If cancelled, recursion terminates immediately with a cancellation error
|
||||
@@ -92,9 +92,9 @@ import (
|
||||
//
|
||||
// # Example: Cancellable Countdown
|
||||
//
|
||||
// countdownStep := func(n int) readerioresult.ReaderIOResult[tailrec.Trampoline[int, string]] {
|
||||
// return func(ctx context.Context) ioeither.IOEither[error, tailrec.Trampoline[int, string]] {
|
||||
// return func() either.Either[error, tailrec.Trampoline[int, string]] {
|
||||
// countdownStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
// return func(ctx context.Context) IOEither[Trampoline[int, string]] {
|
||||
// return func() Either[Trampoline[int, string]] {
|
||||
// if n <= 0 {
|
||||
// return either.Right[error](tailrec.Land[int]("Done!"))
|
||||
// }
|
||||
@@ -105,7 +105,7 @@ import (
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// countdown := readerioresult.TailRec(countdownStep)
|
||||
// countdown := TailRec(countdownStep)
|
||||
//
|
||||
// // With cancellation
|
||||
// ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond)
|
||||
@@ -119,9 +119,9 @@ import (
|
||||
// processed []string
|
||||
// }
|
||||
//
|
||||
// processStep := func(state ProcessState) readerioresult.ReaderIOResult[tailrec.Trampoline[ProcessState, []string]] {
|
||||
// return func(ctx context.Context) ioeither.IOEither[error, tailrec.Trampoline[ProcessState, []string]] {
|
||||
// return func() either.Either[error, tailrec.Trampoline[ProcessState, []string]] {
|
||||
// processStep := func(state ProcessState) ReaderIOResult[Trampoline[ProcessState, []string]] {
|
||||
// return func(ctx context.Context) IOEither[Trampoline[ProcessState, []string]] {
|
||||
// return func() Either[Trampoline[ProcessState, []string]] {
|
||||
// if len(state.files) == 0 {
|
||||
// return either.Right[error](tailrec.Land[ProcessState](state.processed))
|
||||
// }
|
||||
@@ -140,7 +140,7 @@ import (
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// processFiles := readerioresult.TailRec(processStep)
|
||||
// processFiles := TailRec(processStep)
|
||||
// ctx, cancel := context.WithCancel(t.Context())
|
||||
//
|
||||
// // Can be cancelled at any point during processing
|
||||
@@ -158,7 +158,7 @@ import (
|
||||
// still respecting context cancellation:
|
||||
//
|
||||
// // Safe for very large inputs with cancellation support
|
||||
// largeCountdown := readerioresult.TailRec(countdownStep)
|
||||
// largeCountdown := TailRec(countdownStep)
|
||||
// ctx := t.Context()
|
||||
// result := largeCountdown(1000000)(ctx)() // Safe, no stack overflow
|
||||
//
|
||||
@@ -171,11 +171,11 @@ import (
|
||||
//
|
||||
// # See Also
|
||||
//
|
||||
// - [readerioresult.TailRec]: Base tail recursion without automatic context checking
|
||||
// - [WithContext]: Context cancellation wrapper used internally
|
||||
// - [Chain]: For sequencing ReaderIOResult computations
|
||||
// - [Ask]: For accessing the context
|
||||
// - [Left]/[Right]: For creating error/success values
|
||||
// - readerioresult.TailRec: Base tail recursion without automatic context checking
|
||||
// - WithContext: Context cancellation wrapper used internally
|
||||
// - Chain: For sequencing ReaderIOResult computations
|
||||
// - Ask: For accessing the context
|
||||
// - Left/Right: For creating error/success values
|
||||
//
|
||||
//go:inline
|
||||
func TailRec[A, B any](f Kleisli[A, Trampoline[A, B]]) Kleisli[A, B] {
|
||||
|
||||
@@ -30,6 +30,16 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// CustomError is a test error type
|
||||
type CustomError struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *CustomError) Error() string {
|
||||
return fmt.Sprintf("error %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
func TestTailRec_BasicRecursion(t *testing.T) {
|
||||
// Test basic countdown recursion
|
||||
countdownStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
@@ -432,3 +442,237 @@ func TestTailRec_ContextWithValue(t *testing.T) {
|
||||
|
||||
assert.Equal(t, E.Of[error]("Done!"), result)
|
||||
}
|
||||
|
||||
func TestTailRec_MultipleErrorTypes(t *testing.T) {
|
||||
// Test that different error types are properly handled
|
||||
errorStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, string]] {
|
||||
return func() Either[Trampoline[int, string]] {
|
||||
if n == 5 {
|
||||
customErr := &CustomError{Code: 500, Message: "custom error"}
|
||||
return E.Left[Trampoline[int, string]](error(customErr))
|
||||
}
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int]("Done!"))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[string](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
errorRecursion := TailRec(errorStep)
|
||||
result := errorRecursion(10)(t.Context())()
|
||||
|
||||
assert.True(t, E.IsLeft(result))
|
||||
err := E.ToError(result)
|
||||
customErr, ok := err.(*CustomError)
|
||||
require.True(t, ok, "Expected CustomError type")
|
||||
assert.Equal(t, 500, customErr.Code)
|
||||
assert.Equal(t, "custom error", customErr.Message)
|
||||
}
|
||||
|
||||
func TestTailRec_ContextCancelDuringBounce(t *testing.T) {
|
||||
// Test cancellation happens between bounces, not during computation
|
||||
var iterationCount int32
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
|
||||
slowStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, string]] {
|
||||
return func() Either[Trampoline[int, string]] {
|
||||
count := atomic.AddInt32(&iterationCount, 1)
|
||||
|
||||
// Cancel after 3 iterations
|
||||
if count == 3 {
|
||||
cancel()
|
||||
}
|
||||
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int]("Done!"))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[string](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slowRecursion := TailRec(slowStep)
|
||||
result := slowRecursion(10)(ctx)()
|
||||
|
||||
// Should be cancelled after a few iterations
|
||||
assert.True(t, E.IsLeft(result))
|
||||
iterations := atomic.LoadInt32(&iterationCount)
|
||||
assert.Greater(t, iterations, int32(2))
|
||||
assert.Less(t, iterations, int32(10))
|
||||
}
|
||||
|
||||
func TestTailRec_EmptyState(t *testing.T) {
|
||||
// Test with empty/zero-value state
|
||||
type EmptyState struct{}
|
||||
|
||||
emptyStep := func(state EmptyState) ReaderIOResult[Trampoline[EmptyState, int]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[EmptyState, int]] {
|
||||
return func() Either[Trampoline[EmptyState, int]] {
|
||||
return E.Right[error](tailrec.Land[EmptyState](42))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emptyRecursion := TailRec(emptyStep)
|
||||
result := emptyRecursion(EmptyState{})(t.Context())()
|
||||
|
||||
assert.Equal(t, E.Of[error](42), result)
|
||||
}
|
||||
|
||||
func TestTailRec_PointerState(t *testing.T) {
|
||||
// Test with pointer state to ensure proper handling
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
// Create a linked list: 1 -> 2 -> 3 -> nil
|
||||
list := &Node{Value: 1, Next: &Node{Value: 2, Next: &Node{Value: 3, Next: nil}}}
|
||||
|
||||
sumStep := func(node *Node) ReaderIOResult[Trampoline[*Node, int]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[*Node, int]] {
|
||||
return func() Either[Trampoline[*Node, int]] {
|
||||
if node == nil {
|
||||
return E.Right[error](tailrec.Land[*Node](0))
|
||||
}
|
||||
if node.Next == nil {
|
||||
return E.Right[error](tailrec.Land[*Node](node.Value))
|
||||
}
|
||||
// Accumulate value and continue
|
||||
node.Next.Value += node.Value
|
||||
return E.Right[error](tailrec.Bounce[int](node.Next))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sumList := TailRec(sumStep)
|
||||
result := sumList(list)(t.Context())()
|
||||
|
||||
assert.Equal(t, E.Of[error](6), result) // 1 + 2 + 3 = 6
|
||||
}
|
||||
|
||||
func TestTailRec_ConcurrentCancellation(t *testing.T) {
|
||||
// Test that cancellation works correctly with concurrent operations
|
||||
var iterationCount int32
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
|
||||
slowStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, string]] {
|
||||
return func() Either[Trampoline[int, string]] {
|
||||
atomic.AddInt32(&iterationCount, 1)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int]("Done!"))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[string](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slowRecursion := TailRec(slowStep)
|
||||
|
||||
// Cancel from another goroutine after 50ms
|
||||
go func() {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
start := time.Now()
|
||||
result := slowRecursion(20)(ctx)()
|
||||
elapsed := time.Since(start)
|
||||
|
||||
// Should be cancelled
|
||||
assert.True(t, E.IsLeft(result))
|
||||
|
||||
// Should complete quickly due to cancellation
|
||||
assert.Less(t, elapsed, 100*time.Millisecond)
|
||||
|
||||
// Should have executed some but not all iterations
|
||||
iterations := atomic.LoadInt32(&iterationCount)
|
||||
assert.Greater(t, iterations, int32(0))
|
||||
assert.Less(t, iterations, int32(20))
|
||||
}
|
||||
|
||||
func TestTailRec_NestedContextValues(t *testing.T) {
|
||||
// Test that nested context values are preserved
|
||||
type contextKey string
|
||||
const (
|
||||
key1 contextKey = "key1"
|
||||
key2 contextKey = "key2"
|
||||
)
|
||||
|
||||
nestedStep := func(n int) ReaderIOResult[Trampoline[int, string]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, string]] {
|
||||
return func() Either[Trampoline[int, string]] {
|
||||
val1 := ctx.Value(key1)
|
||||
val2 := ctx.Value(key2)
|
||||
|
||||
require.NotNil(t, val1)
|
||||
require.NotNil(t, val2)
|
||||
assert.Equal(t, "value1", val1.(string))
|
||||
assert.Equal(t, "value2", val2.(string))
|
||||
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int]("Done!"))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[string](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nestedRecursion := TailRec(nestedStep)
|
||||
|
||||
ctx := context.WithValue(t.Context(), key1, "value1")
|
||||
ctx = context.WithValue(ctx, key2, "value2")
|
||||
|
||||
result := nestedRecursion(3)(ctx)()
|
||||
|
||||
assert.Equal(t, E.Of[error]("Done!"), result)
|
||||
}
|
||||
|
||||
func BenchmarkTailRec_SimpleCountdown(b *testing.B) {
|
||||
countdownStep := func(n int) ReaderIOResult[Trampoline[int, int]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, int]] {
|
||||
return func() Either[Trampoline[int, int]] {
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int](0))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[int](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
countdown := TailRec(countdownStep)
|
||||
ctx := context.Background()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = countdown(1000)(ctx)()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTailRec_WithCancellation(b *testing.B) {
|
||||
countdownStep := func(n int) ReaderIOResult[Trampoline[int, int]] {
|
||||
return func(ctx context.Context) IOEither[Trampoline[int, int]] {
|
||||
return func() Either[Trampoline[int, int]] {
|
||||
if n <= 0 {
|
||||
return E.Right[error](tailrec.Land[int](0))
|
||||
}
|
||||
return E.Right[error](tailrec.Bounce[int](n - 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
countdown := TailRec(countdownStep)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = countdown(1000)(ctx)()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,14 @@ func TestFormatterInterface(t *testing.T) {
|
||||
result := fmt.Sprintf("%q", tramp)
|
||||
assert.Equal(t, "\"Bounce(42)\"", result)
|
||||
})
|
||||
|
||||
t.Run("unknown verb format", func(t *testing.T) {
|
||||
tramp := Bounce[string](42)
|
||||
result := fmt.Sprintf("%x", tramp)
|
||||
assert.Contains(t, result, "%!x")
|
||||
assert.Contains(t, result, "Trampoline[B, L]")
|
||||
assert.Contains(t, result, "Bounce(42)")
|
||||
})
|
||||
}
|
||||
|
||||
// TestGoStringerInterface verifies fmt.GoStringer implementation
|
||||
|
||||
@@ -22,14 +22,18 @@ import (
|
||||
// LogValue implements the slog.LogValuer interface for Trampoline.
|
||||
//
|
||||
// This method allows Trampoline values to be logged using Go's structured logging
|
||||
// (log/slog) with proper representation of their state:
|
||||
// with proper representation of their state:
|
||||
// - When Landed is true: returns a group with a single "landed" attribute containing the Land value
|
||||
// - When Landed is false: returns a group with a single "bouncing" attribute containing the Bounce value
|
||||
//
|
||||
// The implementation ensures that Trampoline values are logged in a structured,
|
||||
// readable format that clearly shows the current state of the tail-recursive computation.
|
||||
//
|
||||
// Example usage:
|
||||
// # Returns
|
||||
//
|
||||
// - slog.Value: A structured log value representing the trampoline state
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// trampoline := tailrec.Bounce[int](42)
|
||||
// slog.Info("Processing", "state", trampoline)
|
||||
|
||||
@@ -8,17 +8,20 @@ import "fmt"
|
||||
// This represents a recursive call in the original algorithm. The computation
|
||||
// will continue by processing the provided state value in the next iteration.
|
||||
//
|
||||
// Type Parameters:
|
||||
// - L: The final result type (land type)
|
||||
// - B: The intermediate state type (bounce type)
|
||||
// # Type Parameters
|
||||
//
|
||||
// - B: The intermediate state type (bounce type)
|
||||
// - L: The final result type (land type)
|
||||
//
|
||||
// # Parameters
|
||||
//
|
||||
// Parameters:
|
||||
// - b: The new intermediate state to process in the next step
|
||||
//
|
||||
// Returns:
|
||||
// - A Trampoline in the "bounce" state containing the intermediate value
|
||||
// # Returns
|
||||
//
|
||||
// Example:
|
||||
// - Trampoline[B, L]: A Trampoline in the "bounce" state containing the intermediate value
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// // Countdown that bounces until reaching zero
|
||||
// func countdownStep(n int) Trampoline[int, int] {
|
||||
@@ -40,17 +43,20 @@ func Bounce[L, B any](b B) Trampoline[B, L] {
|
||||
// a Land trampoline is encountered, the executor should stop iterating and
|
||||
// return the final result.
|
||||
//
|
||||
// Type Parameters:
|
||||
// # Type Parameters
|
||||
//
|
||||
// - B: The intermediate state type (bounce type)
|
||||
// - L: The final result type (land type)
|
||||
//
|
||||
// Parameters:
|
||||
// # Parameters
|
||||
//
|
||||
// - l: The final result value
|
||||
//
|
||||
// Returns:
|
||||
// - A Trampoline in the "land" state containing the final result
|
||||
// # Returns
|
||||
//
|
||||
// Example:
|
||||
// - Trampoline[B, L]: A Trampoline in the "land" state containing the final result
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// // Factorial base case
|
||||
// func factorialStep(state State) Trampoline[State, int] {
|
||||
@@ -66,7 +72,13 @@ func Land[B, L any](l L) Trampoline[B, L] {
|
||||
}
|
||||
|
||||
// String implements fmt.Stringer for Trampoline.
|
||||
//
|
||||
// Returns a human-readable string representation of the trampoline state.
|
||||
// For bounce states, returns "Bounce(value)". For land states, returns "Land(value)".
|
||||
//
|
||||
// # Returns
|
||||
//
|
||||
// - string: A formatted string representation of the trampoline state
|
||||
func (t Trampoline[B, L]) String() string {
|
||||
if t.Landed {
|
||||
return fmt.Sprintf("Land(%v)", t.Land)
|
||||
@@ -75,7 +87,18 @@ func (t Trampoline[B, L]) String() string {
|
||||
}
|
||||
|
||||
// Format implements fmt.Formatter for Trampoline.
|
||||
// Supports various formatting verbs for detailed output.
|
||||
//
|
||||
// Supports various formatting verbs for detailed output:
|
||||
// - %v: Default format (delegates to String)
|
||||
// - %+v: Detailed format with type information
|
||||
// - %#v: Go-syntax representation (delegates to GoString)
|
||||
// - %s: String format
|
||||
// - %q: Quoted string format
|
||||
//
|
||||
// # Parameters
|
||||
//
|
||||
// - f: The format state
|
||||
// - verb: The formatting verb
|
||||
func (t Trampoline[B, L]) Format(f fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
@@ -106,7 +129,13 @@ func (t Trampoline[B, L]) Format(f fmt.State, verb rune) {
|
||||
}
|
||||
|
||||
// GoString implements fmt.GoStringer for Trampoline.
|
||||
//
|
||||
// Returns a Go-syntax representation that could be used to recreate the value.
|
||||
// The output includes the package name, function name, type parameters, and value.
|
||||
//
|
||||
// # Returns
|
||||
//
|
||||
// - string: A Go-syntax representation of the trampoline
|
||||
func (t Trampoline[B, L]) GoString() string {
|
||||
if t.Landed {
|
||||
return fmt.Sprintf("tailrec.Land[%T](%#v)", t.Bounce, t.Land)
|
||||
|
||||
@@ -7,14 +7,21 @@ type (
|
||||
// - Bounce: The computation should continue with a new intermediate state (type B)
|
||||
// - Land: The computation is complete with a final result (type L)
|
||||
//
|
||||
// Type Parameters:
|
||||
// # Type Parameters
|
||||
//
|
||||
// - B: The "bounce" type - intermediate state passed between recursive steps
|
||||
// - L: The "land" type - the final result type when computation completes
|
||||
//
|
||||
// The trampoline pattern allows converting recursive algorithms into iterative ones,
|
||||
// preventing stack overflow for deep recursion while maintaining code clarity.
|
||||
//
|
||||
// Example:
|
||||
// # Design Note
|
||||
//
|
||||
// This type uses a struct with a boolean flag rather than the Either type to avoid
|
||||
// a cyclic dependency. The either package depends on tailrec for its own tail-recursive
|
||||
// operations, so using Either here would create a circular import.
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// // Factorial using trampolines
|
||||
// type State struct { n, acc int }
|
||||
|
||||
Reference in New Issue
Block a user