Skip to content

count is not tail recursive #221

@LiamPack

Description

@LiamPack

I've run into problems with the count function, which lifts 'a parsers to be 'a list parsers, stack overflowing. This is because the current implementation uses a recursive build-up of lifting cons to parsers in a non-tail-recursive fashion:

let count n p =
  if n < 0 
  then fail "count: n < 0"
  else 
    let rec loop = function
      | 0 -> return []
      | n -> lift2 cons p (loop (n - 1))
    in
    loop n

A naiive fix that I have is the following, which changes the above count to be tail-recursive:

(* A tail-recursive implementation of "count" *)
let count_tr n p =
  if n < 0
  then fail "count: n < 0"
  else
    let rec loop acc =
      function
      | 0 -> acc
      | n -> loop (lift2 cons p acc) (n - 1)
    in
    loop (return []) n

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions