Skip to content

prepend: fails for empty list #637

@czeildi

Description

@czeildi

purrr::prepend fails for empty list due to the checking of the before param though (partly based on the documentation) I would expect it to work as base::append by default. Is there a reason for this?

If you agree that it should work for empty lists as well I am happy to submit a PR.

purrr::prepend(list(), "a")
#> Error in purrr::prepend(list(), "a"): before > 0 && before <= n is not TRUE

append("a", list())
#> [[1]]
#> [1] "a"

purrr::prepend(list("b"), "a")
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "b"
append("a", list("b"))
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "b"

Created on 2019-02-10 by the reprex package (v0.2.0).

My first idea for implementation:

function (x, values, before = 1) 
{
    n <- length(x)
    stopifnot(n == 0 || (before > 0 && before <= n))
    if (before == 1) {
        c(values, x)
    }
    else {
        c(x[1:(before - 1)], values, x[before:n])
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorwipwork in progress

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions