relude-1.2.2.0: Safe, performant, user-friendly and lightweight Haskell Standard Library

Copyright | (c) 2018-2023 Kowainik
License | MIT
Maintainer | Kowainik <xrom.xkov@gmail.com>
Stability | Stable
Portability | Portable
Safe Haskell | Safe
Language | Haskell2010

Relude.Extra.Foldable

Description

Contains utility functions for working with tuples.

Since: 0.6.0.0

Synopsis

- foldlSC :: Foldable t => (b -> a -> Either b b) -> b -> t a -> b
- average :: forall a f. (Foldable f, Fractional a) => f a -> Maybe a

# Documentation

foldlSC :: Foldable t => (b -> a -> Either b b) -> b -> t a -> b #

A left-associative fold that's tail-recursive but can still short-circuit. Returning a `Left` short-circuits and immediately returns the value inside. Returning a `Right` continues the fold as usual with the value inside.

    >>> foldlSC (\acc x -> if x == 0 then Left 0 else Right $! acc * x) 1 [1..6]
    720
    >>> foldlSC (\acc x -> if x == 0 then Left 0 else Right $! acc * x) 1 (0:error "Short-circuiting should keep this from happening")
    0

Since: 0.6.0.0

average :: forall a f. (Foldable f, Fractional a) => f a -> Maybe a #

Given a `Foldable` of `Fractional` elements, computes the average if possible and returns `Maybe` element.

    >>> average [42]
    Just 42.0
    >>> average @Double [1, 2, 3, 4]
    Just 2.5
    >>> average @Float [1.5, 2.5, 3 ,4]
    Just 2.75
    >>> average []
    Nothing

Since: 1.0.0.0