Learn R Programming

hadron (version 3.1.2)

foldr1: Folds the non-empty list with the binary function

Description

A right fold without the need for a neutral element. Does not work with empty lists.

Usage

foldr1(f, xs)

Arguments

f

function. A binary function that takes two elements of the type contained in xs and returns another such element.

xs

list or vector. Homogenious list or vector of elements.

There is a Reduce function in base R that does left and right folds. It always needs a starting element, which usually is the neutral element with respect to the binary operation. We do not want to specify such a neutral element for certain operations, like +.cf. Still a functional programming style should be supported such that one can use maps and folds.

Examples

Run this code
# NOT RUN {
# We generate some random numbers.
numbers <- rnorm(10)

# The sum is easiest computed with the `sum` function:
sum(numbers)

# If we wanted to implement `sum` ourselves, we can use a right fold to do
# so:
Reduce(`+`, numbers, 0.0)

# With this new function we do not need a neutral element any more, but give
# up the possibility to fold empty lists.
foldr1(`+`, numbers)
# }

Run the code above in your browser using DataLab