Skip to content

D43: a recursive function with no return annotation reads its own call as Unit and refuses [] in an arm #2535

Closed

Description

@ehartford

Surfaced by the quicksort with its return type left off (D43: a function with no annotation takes its tail's type):

fn quicksort(xs: List[isize]):
    match xs:
        [] => []
        [pivot, ..rest] =>
            var smaller: List[isize] = []
            var larger: List[isize] = []
            for x in rest:
                if x < pivot: smaller.push(x) else: larger.push(x)
            quicksort(smaller) ++ [pivot] ++ quicksort(larger)

Today (v0.15.3.0-g8182ccfb1):

  • [] => []: error: empty sequence literal requires expected type. The arm has no demand because the return type is what is being inferred.
  • quicksort(smaller) ++ …: error: operand of ++is Unit:quicksort returns Unit. A recursive call reads the function's return as Unit while the body that decides it is being checked.

Expected: the inferred return type is the join of the arms that do not depend on the function itself ([pivot] fixes List[isize] through ++; the other arm's [] takes that demand), and the recursive call has that type. The non-recursive case is D43; this extends it to a body whose tail mentions the function. A body whose every arm is a self-call has no type and says so.

This needs a brief (what the others do: Rust refuses, Swift and Zig infer nothing, OCaml/Haskell unify) before the words land in §9.1 beside D43 and D141. The generic form (fn quicksort[T]) crashes separately, filed with its fix.

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