Skip to main content
Version: v2.2.82 (latest)
Reference · Core Type

ReaderEither

Combine dependency injection (Reader) with custom error handling (Either). ReaderEither[C, E, A] for pure computations with dependencies and custom errors.

01

Overview

type_definition.go
package readereither

// ReaderEither combines Reader and Either
type ReaderEither[C, E, A any] = Reader[C, Either[E, A]]
// Which expands to: func(C) Either[E, A]
02

Core API

Constructors

FunctionSignatureDescription
Rightfunc Right[C, E, A any](value A) ReaderEither[C, E, A]Create successful value
Leftfunc Left[C, E, A any](err E) ReaderEither[C, E, A]Create error value
Offunc Of[C, E, A any](value A) ReaderEither[C, E, A]Alias for Right
Askfunc Ask[C, E any]() ReaderEither[C, E, C]Access context
Asksfunc Asks[C, E, A any](f func(C) A) ReaderEither[C, E, A]Access and transform context

Transformations

FunctionSignatureDescription
Mapfunc Map[C, E, A, B any](f func(A) B) func(ReaderEither[C, E, A]) ReaderEither[C, E, B]Transform success value
MapLeftfunc MapLeft[C, A, E1, E2 any](f func(E1) E2) func(ReaderEither[C, E1, A]) ReaderEither[C, E2, A]Transform error
Chainfunc Chain[C, E, A, B any](f func(A) ReaderEither[C, E, B]) func(ReaderEither[C, E, A]) ReaderEither[C, E, B]Sequence operations
03

Usage Examples

Basic Usage

basic.go
package main

import (
  RE "github.com/IBM/fp-go/v2/readereither"
)

type Config struct {
  MaxRetries int
  Timeout    time.Duration
}

type ValidationError struct {
  Field   string
  Message string
}

func validateRetries() RE.ReaderEither[Config, ValidationError, int] {
  return RE.Asks(func(cfg Config) either.Either[ValidationError, int] {
      if cfg.MaxRetries < 1 {
          return either.Left[int](ValidationError{
              Field:   "maxRetries",
              Message: "must be at least 1",
          })
      }
      return either.Right[ValidationError](cfg.MaxRetries)
  })
}

func main() {
  cfg := Config{MaxRetries: 3, Timeout: time.Second}
  result := validateRetries()(cfg)
  // Either[ValidationError, int]
}