Copyright | © Frank Jung 2020 |
---|---|
License | GPL-3 |
Safe Haskell | Safe-Inferred |
Language | Haskell2010 |
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.
sumTillNegative
: A baseline implementation usingsum
andtakeWhile
.sumTillNegative'
: A strict, tail-recursive version.sumTillNegative''
: An implementation usingfoldr
with continuation-passing style.sumTillNegative'''
: Uses a generic_foldTerminate
helper that employs theEither
monad for early exit.
Synopsis
- sumTillNegative :: [Int] -> Int
- sumTillNegative' :: [Int] -> Int
- sumTillNegative'' :: [Int] -> Int
- sumTillNegative''' :: [Int] -> Int
Documentation
sumTillNegative :: [Int] -> Int Source #
Basic implementation.
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