Files
pylisp/core/evaluator/utils/getFirstN.py
T

32 lines
809 B
Python

from typing import Any
from core.primitives.list import cons, car, cdr, NIL
from core.exceptions import syntaxError
from core.printer import Representation
def getFirstN(_list: Any, n: int) -> list[Any]:
"""Get first N elements.
Args:
_list: A list.
n: The expected number of elements.
Returns:
A list of the extracted elements.
Raises:
syntaxError: If the list has wrong number of elements.
"""
result: list[Any] = []
current: Any = _list
while current != NIL and len(result) < n:
result.append(car(current))
current = cdr(current)
if current != NIL:
raise syntaxError(f"extra elems: {Representation(current)}")
if len(result) < n:
raise syntaxError("lack of elems")
return result