fp-go-loom

module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: BSD-2-Clause

README

fp-go-loom

Go Reference CI/CD License

Reusable fp-go v2 combinators — predicates, ord/eq instances, parse helpers, option pattern-matching, and IOEither/Either bridges. Woven on top of fp-go v2; importable by any Go project.

Table of Contents

Prerequisites

Install

go get github.com/dictyBase/fp-go-loom

Packages

Package Exports
array Compact, ParseWith
either/parse ParseInt
eithererr ConstErr
endomorphism BuildFrom
ioeitherutils ToEither
matchopt Case, Const, Default, Alt, First, Match
predicate/ord IntOrd, Float64Ord, IntEq, Float64Eq, StringEq, IntBetween, IntBetweenInclusive, MinStrLen, MaxStrLen, StrLenEq, NotEqualF64, NotEqualInt, NotEqualStr, StrEq
predicate/array IsNonEmpty, MinLen, MaxLen, LenEq
predicate/bytes HasPositiveLen, IsNonEmpty
predicate/strings LastIndexOf, HasSuffix, ContainsRuneClass, HasAtSign, StrLenBetween
predicate/fs IsDir, IsRegular, IsDirInfo, IsRegularInfo
strutils JoinStrings, Space, Comma, Semicolon, Colon, Label, MiddleDot, EmDash, Newline, JoinSpace, JoinComma, JoinSemicolon, JoinMiddleDot, JoinLines, CollapseWhitespace, Wrap, Parens, Brackets, Quote, Period, MapNonEmpty, ConcatFields
pipelinecheck Check, Require, Config, Violation, Reporter, ModuleRoot, CheckBareIf, RequireBareIf, CheckNoIfErrInTryCatch, RequireNoIfErrInTryCatch, CheckNoHandRolledFileJoinInArrayMap, RequireNoHandRolledFileJoinInArrayMap, CheckNoNonRawTryCatchCallback, RequireNoNonRawTryCatchCallback, CheckSafePrintf, RequireSafePrintf, CheckRedundantFold, RequireNoRedundantFold, CheckTerminalEffect, RequireTerminalEffect, CheckTrivialDelegate, RequireTrivialDelegate, CheckNoImperativeLoop, RequireNoImperativeLoop, CheckNoImperativeBranch, RequireNoImperativeBranch, CheckNoDirectApply, RequireNoDirectApply, CheckNoNewPipe, RequireNoNewPipe, CheckNoBoolExpr, RequireNoBoolExpr, CheckNoFlap, RequireNoFlap, CheckNoPopulatedStruct, RequireNoPopulatedStruct, CheckNoLocalPipeClosure, RequireNoLocalPipeClosure, FunctionPkgPath, ArrayPkgPath, FilepathPkgPath, IOEitherPkgPath, IOPkgPath, EitherPkgPath, OptionPkgPath, EndomorphismPkgPath, DefaultAllowDirective, DefaultAllowAppliedSeedDirective, DefaultAllowBareIfDirective, DefaultAllowTryCatchIfErrDirective, DefaultAllowHandRolledFileJoinDirective, DefaultAllowNonRawTryCatchDirective, DefaultAllowUnsafePrintfDirective, DefaultAllowRedundantFoldDirective, DefaultAllowDuplicateTerminalDirective, DefaultAllowRecoveryAfterTerminalDirective, DefaultAllowTrivialDelegateDirective, DefaultAllowLoopDirective, DefaultAllowBranchDirective, DefaultAllowDirectApplyDirective, DefaultAllowNewPipeDirective, DefaultAllowBoolExprDirective, DefaultAllowFlapDirective, DefaultAllowPopulatedStructDirective, DefaultAllowLocalPipeClosureDirective. All rules ignore generated source.

Note: package names may differ from the import path's last segment (e.g. array → arrutils, predicate/ord → predord). Alias explicitly as shown in the examples below.

Usage

Each snippet shows the package import and a representative call; outputs are shown in comments. Full signatures live on pkg.go.dev.

Arrays
import (
    "strconv"

    O "github.com/IBM/fp-go/v2/option"
    arrutils "github.com/dictyBase/fp-go-loom/array"
)

// Compact: drop None, keep Some values (catMaybes)
opts := []O.Option[string]{
    O.Some("a"), O.None[string](), O.Some("b"),
}
arrutils.Compact[string](opts) // []string{"a", "b"}

// ParseWith: map []string to []A, silently discarding parse errors
parseInts := arrutils.ParseWith(strconv.Atoi)
parseInts([]string{"1", "bad", "42", "x", "7"}) // []int{1, 42, 7}
Endomorphism builders

BuildFrom makes a struct from one input, for example a CLI context. Each recipe reads one value from the input and returns a lens setter. The builder applies the setters in list order to the zero struct.

import (
    En "github.com/IBM/fp-go/v2/endomorphism"
    F "github.com/IBM/fp-go/v2/function"
    endoutils "github.com/dictyBase/fp-go-loom/endomorphism"
    "github.com/urfave/cli/v2"
)

// Params, inputL, outputL, flagString, and c come from the
// consumer code. flagString is (*cli.Context).String.

paramsOf := endoutils.BuildFrom(
    []func(*cli.Context) En.Endomorphism[Params]{
        F.Flow2(F.Bind2nd(flagString, "input"), inputL.Set),
        F.Flow2(F.Bind2nd(flagString, "output"), outputL.Set),
    },
)
paramsOf(c) // Params{Input: ..., Output: ...}

Use BuildFrom only for pure recipes that cannot fail. Use E.Bind or IOE.Bind for a fallible field or a dependent field. When two recipes set the same field, the last recipe wins.

Strings
import "github.com/dictyBase/fp-go-loom/strutils"

strutils.JoinStrings("a", "b", "c") // "abc"
strutils.JoinStrings()             // ""
Separator monoids

Each separator is a M.Monoid[string] built on S.IntersperseMonoid. An empty operand drops out together with its separator, so an optional part needs no branch. Empty() is "", and the monoid laws hold, so you can regroup joins freely.

Monoid Separator Fold over a slice
Space " " JoinSpace
Comma ", " JoinComma
Semicolon "; " JoinSemicolon
Colon ":" —
Label ": " —
MiddleDot " · " JoinMiddleDot
EmDash " — " —
Newline "\n" JoinLines
strutils.Comma.Concat("a", "b")              // "a, b"
strutils.Comma.Concat("a", "")               // "a"
strutils.JoinComma([]string{"a", "", "b"})   // "a, b"
strutils.Label.Concat("Species", "discoideum") // "Species: discoideum"

Fold any slice with another monoid through M.ConcatAll(m), or map and fold in one step with F.Pipe1(f, A.FoldMap(m)):

names := F.Pipe1(lastName, A.FoldMap[Author](strutils.Comma))
names(authors) // "Smith, Jones"
Text helpers
strutils.CollapseWhitespace("  a \t b\n c ") // "a b c"
strutils.Parens("2006")                     // "(2006)"
strutils.Brackets("x")                      // "[x]"
strutils.Quote("x")                         // `"x"`
strutils.Period("Smith")                    // "Smith."
strutils.Wrap("<", ">")("x")                // "<x>"

MapNonEmpty(f) applies f to a non-empty string and returns "" for an empty one. With a separator monoid, it renders an optional part:

doiLink := strutils.MapNonEmpty(toDOILink)
strutils.MiddleDot.Concat(pubmed, doiLink(""))    // pubmed
strutils.MiddleDot.Concat(pubmed, doiLink("10.1")) // pubmed + " · " + link
Join struct fields

ConcatFields[A](m) lifts m to functions with M.FunctionMonoid and folds a list of field projections into one renderer. An empty field drops out with its separator:

name := strutils.ConcatFields[Author](strutils.Space)(
	[]func(Author) string{lastName, initials},
)
name(Author{Last: "Smith", Initials: "A"}) // "Smith A"
name(Author{Last: "Jones"})                // "Jones"
Either & error handling
import (
    E "github.com/IBM/fp-go/v2/either"

    eitherparse "github.com/dictyBase/fp-go-loom/either/parse"
    eithererr "github.com/dictyBase/fp-go-loom/eithererr"
)

// ParseInt: string -> Either[error, int]
eitherparse.ParseInt("42")  // Right[error, int](42)
eitherparse.ParseInt("abc") // Left[error, int]("failed to parse int: ...")
E.IsRight(eitherparse.ParseInt("42")) // true

// ConstErr: stable sentinel error factory. The same errors.New instance is
// returned on every call, so errors.Is stays stable across invocations.
fn := eithererr.ConstErr[string]("invalid")
fn("anything") // error("invalid")
fn("a") == fn("b") // true — identical instance
IOEither bridge
import (
    IOE "github.com/IBM/fp-go/v2/ioeither"

    ioeutils "github.com/dictyBase/fp-go-loom/ioeitherutils"
)

// ToEither: force a lazy IOEither into an eager Either
ioe := IOE.Right[error, int](42)
ioeutils.ToEither[error, int](ioe) // Right[error, int](42)
Option pattern matching
import (
    O "github.com/IBM/fp-go/v2/option"

    MO "github.com/dictyBase/fp-go-loom/matchopt"
)

// Build pattern-match arms over Option
armNeg := MO.Const(func(n int) bool { return n < 0 }, "neg")
armZero := MO.Const(func(n int) bool { return n == 0 }, "zero")
armPos := MO.Default(func(n int) string { return "pos" })

classify := func(n int) string {
    arms := []O.Option[string]{armNeg(n), armZero(n), armPos(n)}
    return MO.First("unknown", arms)
}
classify(-5) // "neg"
classify(0)  // "zero"
classify(7)  // "pos"

// Alt: first Some wins, or None
MO.Alt([]O.Option[int]{
    O.None[int](), O.Some(1), O.Some(2),
}) // Some(1)

// Match: lazy dispatch over unapplied cases — later cases
// never run after a match (expensive guards stay cheap)
numType := MO.Match("unknown", []O.Kleisli[int, string]{
    armNeg, armZero, armPos,
})
numType(0) // "zero"; armPos never invoked
Predicates

Ord/eq instances and derived predicates (predicate/ord):

import predord "github.com/dictyBase/fp-go-loom/predicate/ord"

predord.MinStrLen(3)("hello")            // true — len(s) >= 3
predord.MaxStrLen(5)("hello")            // true — len(s) <= 5
predord.StrLenEq(3)("hey")               // true — len(s) == 3
predord.IntBetween(1, 10)(5)             // true — 1 <= x < 10 (exclusive)
predord.IntBetween(1, 10)(10)            // false
predord.IntBetweenInclusive(1, 10)(10)  // true — inclusive upper
predord.NotEqualInt(5)(6)                // true — x != v
predord.StrEq("go")("go")                // true — x == s

// Base instances to pass into fp-go combinators:
//   predord.IntOrd, predord.Float64Ord,
//   predord.IntEq, predord.Float64Eq, predord.StringEq

Slice-length predicates (predicate/array):

import predarrays "github.com/dictyBase/fp-go-loom/predicate/array"

predarrays.IsNonEmpty[int]()([]int{1})                  // true — len > 0
predarrays.IsNonEmpty[int]()([]int{})                    // false
predarrays.MinLen[string](3)([]string{"a", "b", "c"})    // true — len >= 3
predarrays.MaxLen[string](3)([]string{"a", "b"})         // true — len <= 3
predarrays.LenEq[int](2)([]int{1, 2})                    // true — len == 2

Byte predicates (predicate/bytes):

import predbytes "github.com/dictyBase/fp-go-loom/predicate/bytes"

predbytes.HasPositiveLen([]byte("data")) // true — len > 0
predbytes.HasPositiveLen([]byte{})       // false
predbytes.HasPositiveLen(nil)            // false
predbytes.IsNonEmpty([]byte("x"))        // true — alias for HasPositiveLen

String predicates from curried stdlib (predicate/strings):

import (
    "unicode"

    predstrings "github.com/dictyBase/fp-go-loom/predicate/strings"
)

predstrings.LastIndexOf("@")("foo@bar")                 // 3
predstrings.HasSuffix(".go")("hello.go")               // true
predstrings.ContainsRuneClass(unicode.IsUpper)("Hello") // true
predstrings.HasAtSign("user@example.com")               // true
predstrings.StrLenBetween(3, 5)("hello")                // true — inclusive

File predicates (predicate/fs): atomic predicates on fs.FileInfo plus generic factories that lift them onto a state type:

import predfs "github.com/dictyBase/fp-go-loom/predicate/fs"

// atomic + P.ContraMap + any extractor (field lambda, no lens)
var isDirInfo = F.Pipe1(predfs.IsDirInfo, P.ContraMap(func(s stat) fs.FileInfo {
	return s.info
}))

// factory + lens getter: no lambda, extractor comes from the lens
var isDir = predfs.IsDir(fileInfoLens.Get)
Pipeline and style checks

All pipelinecheck rules ignore files with a full // Code generated ... DO NOT EDIT. line comment. The marker can appear before or after the package clause. This includes fp-go lens output. Generated declarations supply package context for checks of handwritten source. Marker fragments, block comments, and string literals do not stop checks.

pipelinecheck flags fp-go CLI entrypoints that delegate the whole continuation to a single-use wrapper via F.Pipe1(seed, namedFn) instead of inlining the steps into one F.PipeN. Drop a small _test.go into any package whose run*/Action handlers should stay inline:

package cmd

import (
	"strings"
	"testing"

	pipelinecheck "github.com/dictyBase/fp-go-loom/pipelinecheck"
)

func TestPipelineContinuity(t *testing.T) {
	pipelinecheck.Require(t, pipelinecheck.Config{
		Roots: []string{"."},
		IsEntrypoint: func(name string) bool {
			return strings.HasPrefix(name, "run")
		},
	})
}

Opt a genuinely-reused wrapper out with a doc comment carrying a non-empty reason:

// fp-go:allow-pipe1-handoff reused by runA and runB
func runThing(ctx context.Context, c *cli3.Command) error {
	return F.Pipe1(seed(ctx, c), sharedHandler)
}

The function-package alias is resolved from each file's imports, so F, fn, or the default function all work. Analysis is syntax-only (see package doc for limitations).

Point-free branching rule

CheckBareIf flags bare if statements inside function literals passed as callbacks to fp-go Pipe*/Flow*, or to Map, Chain, and ChainFirst from Either, IO, IOEither, and Option. The rule resolves imports by canonical path, so custom aliases work. It ignores ordinary closures and TryCatchError callbacks. Replace branching with a pre-bound P.Fold(onFalse, onTrue) and apply the predicate at the pipeline call site.

Enable it in a project gate with RequirePointFreeBranching:

func TestPointFreeBranching(t *testing.T) {
	pipelinecheck.Require(t, pipelinecheck.Config{
		Roots:                     []string{"."},
		RequirePointFreeBranching: true,
	})
}

Or run the rule directly with RequireBareIf:

pipelinecheck.RequireBareIf(t, pipelinecheck.Config{
	Roots: []string{"."},
})

Opt out only for a documented exception: // fp-go:allow-bare-if <reason>. An empty reason does not suppress violations.

Fixed-root file mapping rule

RequireNoHandRolledFileJoinInArrayMap flags filepath.Join or filepath.FromSlash path construction inside a function literal passed as an fp-go array.Map mapper. The rule resolves imports by canonical path, so custom aliases work, while ordinary joins outside the mapper remain clean. Use one flipped FILE.Join mapper instead:

root := F.Pipe1(st.Path, F.Flip(FILE.Join))
IOE.Map[error](A.Map(root))

The gate does not require exact variable names or Pipe arity. Opt out only with // fp-go:allow-hand-rolled-file-join <reason>.

TryCatch raw-effect rules

RequireNoIfErrInTryCatch flags if err != nil / if nil != err inside an IOE.TryCatchError callback literal. TryCatchError should hold the raw SDK effect; projection and wrapping belong in IOE.MapLeft / IOE.Map. The rule applies to all functions, not just entrypoints. Resolve the IOEither import alias automatically (IOE, ioeither, or a custom alias).

RequireNoNonRawTryCatchCallback complements it by flagging clear fmt.Errorf wrapping, .Set(...) lens-setter calls, and selector-based success projection inside the callback. It does not flag arbitrary helper or SDK calls, and it does not require later MapLeft or Map stages. Opt out with // fp-go:allow-non-raw-trycatch <reason>.

func TestNoNonRawTryCatchCallback(t *testing.T) {
	pipelinecheck.RequireNoNonRawTryCatchCallback(t, pipelinecheck.Config{
		Roots: []string{"."},
	})
}

Opt out of the error-branch rule with // fp-go:allow-trycatch-iferr <reason>.

Safe-Printf rule

RequireSafePrintf flags IO.Printf calls whose literal or package-local constant format string has no real formatting verb. A verb-less format dumps the value via %!(EXTRA type=value) and can leak secrets such as API keys. The rule applies to all functions. The printf directive parser handles flags, [index], width/precision (digits, *, indexed stars), and the documented fmt verbs (%U, %F included; %w excluded — it is only meaningful to fmt.Errorf). Package-local string constants are resolved across files in the same package, including grouped, inherited, and concatenated ones.

func TestSafePrintf(t *testing.T) {
	pipelinecheck.RequireSafePrintf(t, pipelinecheck.Config{
		Roots: []string{"."},
	})
}

Opt out with // fp-go:allow-unsafe-printf <reason>.

Redundant-Fold rule

RequireNoRedundantFold flags E.Fold / E.Match calls whose Right (success) arm discards its argument by returning nil. That shape is "extract the Left error, return nil on Right" — the long form of E.ToError[A]. Two discard shapes are detected: an anonymous func whose body is a single return nil, and a function-package Constant* combinator wrapping nil or a T(nil) conversion. Reserve Fold for the case where both arms produce a real value from their input (durable rule 10).

func TestNoRedundantFold(t *testing.T) {
	pipelinecheck.RequireNoRedundantFold(
		t, pipelinecheck.Config{Roots: []string{"."}},
	)
}

Opt out with // fp-go:allow-redundant-fold <reason>.

Terminal-effect rules

RequireTerminalEffect protects the boundary where a pipeline stops being pure and performs an irreversible effect — a write, a send, a commit, a publish. Such an effect must run exactly once per request, and two shapes silently break that:

  1. Duplicate terminal fold — an E.Fold / IOE.Fold / Match whose two arms both reach a terminal function. The effect is then invoked once per branch, so the call sites drift apart, and a late failure cannot be recovered without emitting a second time.
  2. Recovery after a terminal step — an IOE.OrElse positioned after a terminal step inside the same F.PipeN. A failure raised inside the effect sends the pipeline into the recovery arm, which performs the effect again.

The fix for both is the same: converge the success and failure branches on one description value, then execute once after the convergence.

// flagged: recovery wraps a step that already sent
F.Pipe2(
	IOE.Of[error](msg),
	IOE.Chain(encodeAndSend),
	IOE.OrElse(recoverSend),
)

// clean: recover first, send once at the end
F.Pipe3(
	IOE.Of[error](msg),
	IOE.ChainEitherK(encode),
	IOE.OrElse(encodeFailure),
	IOE.Chain(send),
)

Both rules are inert until the project names its terminal effects, so adopting the gate cannot break an existing build:

func TestTerminalEffect(t *testing.T) {
	pipelinecheck.RequireTerminalEffect(t, pipelinecheck.Config{
		Roots:             []string{"."},
		TerminalFunctions: []string{"writeResponse", "send"},
	})
}

Names are matched bare, so a method such as Send needs no receiver. Reachability follows up to two package-local hops, which covers the common case of a thin wrapper (respondJSON → writeResponse) but not arbitrary call chains — the analysis stays syntax-only.

Opt out with // fp-go:allow-duplicate-terminal <reason> or // fp-go:allow-recovery-after-terminal <reason>.

Trivial-delegate rule

RequireTrivialDelegate (or Config.RequireTrivialDelegate: true in Check/Require) flags three kinds of ceremonial wrapper functions referenced from F.Pipe*, F.Flow*, IOE.*, or lens.Modify in the same package:

  1. Single-statement pass-through calls (func f(x State) IOE.X { return g(x) }) whose arguments only forward the wrapper's own parameters — call g directly at the pipeline call site.
  2. Ignored-parameter pipeline adapters (func f(_ State) IOE.X { return g(...) }) that discard their state parameter and return a single non-closure call — pass F.Constant1[State](g(...)) at the pipeline call site.
  3. Single-use F.PipeN wrappers (func f(s State) M { return F.PipeN(s, ...) }) referenced only once in a linear pipeline step (F.Pipe*, F.Flow*, IOE.Chain*, IOE.Map*, or lens.Modify) with no TryCatch* or MapLeft stage — inline the steps directly into the caller's F.PipeN. The rule flags only a wrapper of one step after the seed (F.Pipe1(x, f)). A wrapper of two or more steps is a named operation, and the rule does not flag it.
func TestTrivialDelegate(t *testing.T) {
	pipelinecheck.RequireTrivialDelegate(t, pipelinecheck.Config{
		Roots: []string{"."},
	})
}

Opt out only for a documented exception: // fp-go:allow-trivial-delegate <reason>.

Imperative loop and branch rules

RequireNoImperativeLoop flags every for and range statement. RequireNoImperativeBranch flags every if, switch, and type switch. Both skip the callback of an fp-go TryCatch* call, because that callback is the imperative shell around a raw effect. The branch rule is stricter than the point-free branching rule: that rule flags only an if inside a pipeline callback, and this rule flags an if in any function.

Replace a loop with A.Map, A.Reduce, A.FilterMap, or A.Traverse*. Replace a branch with O.FromPredicate + O.Fold, P.Fold, E.FromPredicate, or matchopt.

func TestNoImperativeControlFlow(t *testing.T) {
	cfg := pipelinecheck.Config{Roots: []string{"."}}
	pipelinecheck.RequireNoImperativeLoop(t, cfg)
	pipelinecheck.RequireNoImperativeBranch(t, cfg)
}

Some APIs only offer a mutable call, for example ast.Node.AppendChild. Wrap that call in one named adapter and opt out with a reason. The directive applies to the whole function:

// fp-go:allow-loop goldmark nodes are mutable; AppendChild is the only API
func withChildren(parent ast.Node, kids []ast.Node) ast.Node {
	for _, kid := range kids {
		parent.AppendChild(parent, kid)
	}
	return parent
}

Opt out with // fp-go:allow-loop <reason> or // fp-go:allow-branch <reason>.

Direct-apply rule

RequireNoDirectApply flags comb(args)(value) in a file that imports fp-go or fp-go-loom, for example A.Map(f)(xs). That shape reads inside-out. Write F.Pipe1(xs, A.Map(f)) so the data flows left to right.

func TestNoDirectApply(t *testing.T) {
	pipelinecheck.RequireNoDirectApply(
		t, pipelinecheck.Config{Roots: []string{"."}},
	)
}

The rule does not flag an fp-go call that takes a plain call as an argument, such as P.Or(hasCode(x)). That shape is a valid partial application, and syntax alone cannot tell it from data nesting.

Opt out with // fp-go:allow-direct-apply <reason>.

New-pipe rule

RequireNoNewPipe flags new(F.PipeN(...)) and new(F.FlowN(...)). Return the value from the pipeline. Take its address with &v only at the API call that needs a pointer. Opt out with // fp-go:allow-new-pipe <reason>.

Bool-expression rule

RequireNoBoolExpr flags a named function with one parameter and a bool result when its return expression uses ==, !=, <, <=, >, >=, &&, ||, or !. Build the predicate from P.And, P.Or, P.Not, predord, and F.Flow2(getter, pred). The rule does not flag a function of two or more parameters. Opt out with // fp-go:allow-bool-expr <reason>.

Flap rule

RequireNoFlap flags each use of Flap or MonadFlap from any fp-go v2 package, and each use of function.Flip. The rule flags a call and a function value, such as F.Flip(A.Flap[string, T]). These combinators hide a plain call f(x) or a plain argument order. Write a named function that calls f(x) or takes its arguments in the order that you need.

// Flagged: rows rendered through a flipped Flap.
A.Map(F.Pipe2(cols, A.Map(PR.Tail), F.Flip(A.Flap[string, T])))

// Clean: one named function per row type.
func recordFields(r Record) []string {
	return []string{recordL.StrainID.Get(r), recordL.Note.Get(r)}
}

A Flap is allowed when an enclosing call also takes a step from github.com/IBM/fp-go/v2/endomorphism, as in F.Pipe2(edits, A.Flap[En.Endomorphism[T]](x), En.Reduce[T]). endoutils.BuildFrom already hides that pattern, so use it first. Opt out with // fp-go:allow-flap <reason>.

Populated-struct rule

RequireNoPopulatedStruct flags populated struct composite literals (T{Field: value}, &T{Field: value}, []T{{Field: value}}) in files that import fp-go or fp-go-loom. Start from the empty zero struct T{} and populate fields with lens.Set in F.PipeN instead:

func buildPerson() Person {
	return F.Pipe2(
		Person{},
		nameLens.Set("Alice"),
		ageLens.Set(30),
	)
}

Empty zero literals (T{}), slice literals, and map literals remain clean.

func TestNoPopulatedStruct(t *testing.T) {
	pipelinecheck.RequireNoPopulatedStruct(
		t, pipelinecheck.Config{Roots: []string{"."}},
	)
}

Opt out with // fp-go:allow-struct-literal <reason>.

Local-pipe-closure rule

RequireNoLocalPipeClosure flags four local assignment shapes inside functions in files that import fp-go or fp-go-loom (outside TryCatch* raw-effect callbacks):

  1. Local closure variables (toInput := func(x X) Y { ... }) — extract a standalone package-level function and bind state with F.Bind1st / F.Bind2nd.
  2. Local F.Flow* pipelines (extractRoot := F.Flow3(...)) — move reusable pipelines to the package-level var block or inline their steps into one flat F.PipeN.
  3. Split F.Pipe* seeds (inputs := F.Pipe1(...); return F.Pipe2(inputs, ...)) — combine both into one flat F.PipeN.
  4. Local fp-go combinator assignments (traverse := IOE.TraverseArray(exec)) referenced as pipeline or combinator steps — move them to the package-level var block or inline them at the step.
func TestNoLocalPipeClosure(t *testing.T) {
	pipelinecheck.RequireNoLocalPipeClosure(
		t, pipelinecheck.Config{Roots: []string{"."}},
	)
}

Opt out with // fp-go:allow-local-pipe-closure <reason>.

Pipelines

The fp-go-concepts examples chain multiple combinators with F.Pipe to build real-world flows. These four pipelines show loom functions composed across packages. Every snippet was verified to compile and its asserted output to hold before transcription.

Either validation chain

Monadic E.Chain threads a value through stages; each E.FromPredicate fails fast with a stable sentinel from eithererr.ConstErr, so errors.Is keeps identity across calls.

import (
    E "github.com/IBM/fp-go/v2/either"
    F "github.com/IBM/fp-go/v2/function"
    Str "github.com/IBM/fp-go/v2/string"

    eithererr "github.com/dictyBase/fp-go-loom/eithererr"
    predord "github.com/dictyBase/fp-go-loom/predicate/ord"
)

func ValidateUsername(username string) E.Either[error, string] {
    return F.Pipe3(
        username,
        E.FromPredicate(
            Str.IsNonEmpty,
            eithererr.ConstErr[string]("username is required"),
        ),
        E.Chain(E.FromPredicate(
            predord.MinStrLen(3),
            eithererr.ConstErr[string](
                "username must be at least 3 characters",
            ),
        )),
        E.Chain(E.FromPredicate(
            predord.MaxStrLen(20),
            eithererr.ConstErr[string](
                "username must be at most 20 characters",
            ),
        )),
    )
}

ValidateUsername("alice") // Right[error, string]("alice")
ValidateUsername("")      // Left — "username is required"
ValidateUsername("ab")    // Left — "username must be at least 3 characters"
Parse and range-validate

eitherparse.ParseInt returns Either; E.Chain composes it with a range check built from predord.IntBetween. Parse failure and range failure surface as distinct lefts.

import (
    E "github.com/IBM/fp-go/v2/either"
    F "github.com/IBM/fp-go/v2/function"

    eitherparse "github.com/dictyBase/fp-go-loom/either/parse"
    eithererr "github.com/dictyBase/fp-go-loom/eithererr"
    predord "github.com/dictyBase/fp-go-loom/predicate/ord"
)

func ParsePort(portStr string) E.Either[error, int] {
    return F.Pipe1(
        eitherparse.ParseInt(portStr),
        E.Chain(E.FromPredicate(
            predord.IntBetween(1, 65536),
            eithererr.ConstErr[int](
                "port must be between 1 and 65535",
            ),
        )),
    )
}

ParsePort("8080") // Right[error, int](8080)
ParsePort("abc")  // Left — "failed to parse int: ..."
ParsePort("70000") // Left — "port must be between 1 and 65535"
CSV parse and filter

A.FilterMap keeps rows whose split passes predarrays.LenEq; each kept row is mapped into a struct via O.Map.

import (
    "strings"

    A "github.com/IBM/fp-go/v2/array"
    F "github.com/IBM/fp-go/v2/function"
    O "github.com/IBM/fp-go/v2/option"

    predarrays "github.com/dictyBase/fp-go-loom/predicate/array"
)

type Customer struct{ ID, Name string }

func ParseCustomers(lines []string) []Customer {
    return F.Pipe1(
        lines,
        A.FilterMap(func(line string) O.Option[Customer] {
            parts := strings.Split(line, ",")
            return F.Pipe2(
                parts,
                O.FromPredicate(predarrays.LenEq[string](2)),
                O.Map(func(p []string) Customer {
                    return Customer{ID: p[0], Name: p[1]}
                }),
            )
        }),
    )
}

ParseCustomers([]string{"1,Alice", "bad", "2,Bob", "3,Carol,Extra"})
// []Customer{{ID:"1", Name:"Alice"}, {ID:"2", Name:"Bob"}}
Password strength classification

predstrings.ContainsRuneClass and predord.MinStrLen/MaxStrLen compose into strength predicates via Pred.And; matchopt.Const + First classify. Strong implies medium, so arms run most-specific first.

import (
    "unicode"

    F "github.com/IBM/fp-go/v2/function"
    O "github.com/IBM/fp-go/v2/option"
    Pred "github.com/IBM/fp-go/v2/predicate"

    MO "github.com/dictyBase/fp-go-loom/matchopt"
    predord "github.com/dictyBase/fp-go-loom/predicate/ord"
    predstrings "github.com/dictyBase/fp-go-loom/predicate/strings"
)

func ClassifyPassword(pw string) string {
    hasUpper := predstrings.ContainsRuneClass(unicode.IsUpper)
    hasLower := predstrings.ContainsRuneClass(unicode.IsLower)
    hasDigit := predstrings.ContainsRuneClass(unicode.IsDigit)
    isLongEnough := predord.MinStrLen(8)
    isShort := predord.MaxStrLen(7)

    medium := F.Pipe2(
        isLongEnough, Pred.And(hasUpper), Pred.And(hasLower),
    )
    strong := F.Pipe1(medium, Pred.And(hasDigit))

    armStrong := MO.Const(strong, "strong")
    armMedium := MO.Const(medium, "medium")
    armWeak := MO.Const(isShort, "weak")

    return MO.First("unknown", []O.Option[string]{
        armStrong(pw), armMedium(pw), armWeak(pw),
    })
}

ClassifyPassword("123")         // "weak"
ClassifyPassword("Password")    // "medium"
ClassifyPassword("Password123") // "strong"

Project Structure

.
├── array/
│   ├── array.go               # Compact, ParseWith
│   └── array_test.go
├── endomorphism/
│   ├── endomorphism.go        # BuildFrom
│   └── endomorphism_test.go
├── either/
│   └── parse/
│       ├── parse.go           # ParseInt
│       └── parse_test.go
├── eithererr/
│   ├── errors.go              # ConstErr
│   └── errors_test.go
├── ioeitherutils/
│   └── ioeitherutils.go       # ToEither
├── matchopt/
│   └── matchopt.go            # Case, Const, Default, Alt, First, Match
├── predicate/
│   ├── ord/
│   │   ├── ord.go             # IntOrd, IntBetween, MinStrLen, ...
│   │   └── ord_test.go
│   ├── array/
│   │   ├── array.go           # IsNonEmpty, MinLen, MaxLen, LenEq
│   │   └── array_test.go
│   ├── bytes/
│   │   ├── bytes.go           # HasPositiveLen, IsNonEmpty
│   │   └── bytes_test.go
│   └── strings/
│       ├── strings.go         # LastIndexOf, HasSuffix, HasAtSign, ...
│       └── strings_test.go
├── strutils/
│   ├── strutils.go            # JoinStrings
│   ├── monoid.go              # separator monoids, Wrap, MapNonEmpty, ConcatFields
│   ├── monoid_test.go
│   └── strutils_test.go
└── pipelinecheck/
    ├── pipelinecheck.go       # Check, Require, Config, Violation
    ├── bareif.go              # Point-free branching rule
    ├── trycatch.go            # NoIfErrInTryCatch rule
    ├── controlflow.go         # Imperative loop + branch rules
    ├── directapply.go         # Direct-apply rule
    ├── printf.go              # SafePrintf rule + const resolution
    ├── pipelinecheck_test.go  # handoff + applied-seed tests
    └── stylecheck_test.go     # trycatch + printf tests

Development

# Run tests
gotestsum --format pkgname-and-test-fails --format-hide-empty-pkg -- ./...

# Run tests with verbose output
gotestsum --format testdox -- ./...

# Lint
golangci-lint run ./...

# Format (gofumpt + goimports + golines)
golangci-lint fmt

License

BSD-2-Clause. See LICENSE.

Directories

Path Synopsis
Package arrutils provides generic array utility functions built with fp-go v2 combinators.
Package arrutils provides generic array utility functions built with fp-go v2 combinators.
either
parse
Package eitherparse provides functions to parse strings into various types, returning Either[error, T] to handle parsing errors gracefully.
Package eitherparse provides functions to parse strings into various types, returning Either[error, T] to handle parsing errors gracefully.
Package eithererr provides utilities for working with functions that return either a value or an error.
Package eithererr provides utilities for working with functions that return either a value or an error.
Package endoutils provides builders on top of fp-go v2 endomorphisms.
Package endoutils provides builders on top of fp-go v2 endomorphisms.
examples
pipelinecheck command
Package main is a runnable example of a pipelinecheck gate over a compliant fp-go CLI entrypoint.
Package main is a runnable example of a pipelinecheck gate over a compliant fp-go CLI entrypoint.
Package ioeitherutils provides utility functions for working with IOEither.
Package ioeitherutils provides utility functions for working with IOEither.
Package loomcheck enforces "import the loom combinator instead of hand-rolling it" through a syntax-only AST check.
Package loomcheck enforces "import the loom combinator instead of hand-rolling it" through a syntax-only AST check.
Package matchopt provides helpers for building Option-based pattern-match arms.
Package matchopt provides helpers for building Option-based pattern-match arms.
Package pipelinecheck enforces fp-go style rules via syntax-only AST checks.
Package pipelinecheck enforces fp-go style rules via syntax-only AST checks.
predicate
array
Package predarrays provides generic slice-length predicates built with fp-go v2 combinators.
Package predarrays provides generic slice-length predicates built with fp-go v2 combinators.
bytes
Package predbytes provides predicates for []byte.
Package predbytes provides predicates for []byte.
fs
Package fs provides predicates over io/fs.FileInfo, derived from the FileInfo interface methods.
Package fs provides predicates over io/fs.FileInfo, derived from the FileInfo interface methods.
ord
Package predord provides reusable fp-go ord/eq instances and derived predicates.
Package predord provides reusable fp-go ord/eq instances and derived predicates.
strings
Package predstrings provides predicates on strings, derived from curried stdlib string functions.
Package predstrings provides predicates on strings, derived from curried stdlib string functions.
Package strutils provides utility functions for string operations using fp-go functional patterns.
Package strutils provides utility functions for string operations using fp-go functional patterns.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL