Scrapbook-0.4.0: code examples
Copyright© Frank Jung 2020
LicenseGPL-3
Safe HaskellSafe-Inferred
LanguageHaskell2010

TermFold

Description

This module explores different techniques for folding over a list with the ability to terminate early. It serves as a practical example of control flow patterns in Haskell, including strict folds, continuation-passing style (CPS), and monadic control flow with Either.

This module focuses on the foundational concept of using a monad (Either) for short-circuiting.

Code based on FPComplete Folds with early termination

The functions are defined to sum a list of integers, stopping when a negative value is encountered.

  1. sumTillNegative: A baseline implementation using sum and takeWhile.
  2. sumTillNegative': A strict, tail-recursive version.
  3. sumTillNegative'': An implementation using foldr with continuation-passing style.
  4. sumTillNegative''': Uses a generic _foldTerminate helper that employs the Either monad for early exit.
Synopsis

Documentation

sumTillNegative :: [Int] -> Int Source #

Basic implementation.

baseline implementation using sum and takeWhile

sumTillNegative' :: [Int] -> Int Source #

Fold strict sum with early termination.

This function: * uses a strict accumulator (total) for efficiency * recursively adds values until a negative is found or the list ends * returns the sum up to (but not including) the first negative

strict, tail-recursive version

sumTillNegative'' :: [Int] -> Int Source #

Using foldr with continuation passing style. This approach leverages Haskell's laziness by using continuations to short-circuit computation when encountering a negative value.

This function: * Single-pass processing * Clean, declarative style * Explicit control over strictness

continuation-passing style with foldr

sumTillNegative''' :: [Int] -> Int Source #

Returns either the total (left value) or the current accumulation and the rest of the list. The left value will terminate the loop. See also either

uses Either for early exit