luminyra
Guides

Either and its two branches

Model text or integers, fold both branches to one result type, and transform one side independently.

Fold two input types into one output type

The example tries to parse the input as an integer. It uses Right for the integer on success and Left to keep the original string on failure. Both branches represent valid forms of input. Either.Fold calls only the function for the active branch. Here, both functions return strings.

fp/examples/either/main.go
// Input that parses as a number goes right; anything else stays left.
parse := func(s string) fp.Either[string, int] {
	if n, err := strconv.Atoi(s); err == nil {
		return fp.Right[string](n)
	}
	return fp.Left[string, int](s)
}

for _, s := range []string{"42", "hello"} {
	e := parse(s)
	desc := e.Fold(
		func(text string) string { return "text " + strconv.Quote(text) },
		func(n int) string { return fmt.Sprintf("number %d, doubled %d", n, n*2) },
	)
	fmt.Printf("%-13v -> %s\n", e, desc)
}
View on GitHub

Transform only the right side

Either.MapRight transforms the value on the right and can change its type. Either.Right exposes the right side as an Option for further processing. Either.Swap exchanges the branches and their types.

fp/examples/either/main.go
// MapRight transforms only the right side and may change its type; Right
// returns the right value as an Option.
doubled := parse("21").MapRight(func(n int) int { return n * 2 })
fmt.Println(doubled, doubled.Right())
fmt.Println(parse("7").Swap())
View on GitHub

On this page