from typing import Optional


def to_field_element(val: int, prime: Optional[int]) -> int:
    """
    Converts val to an integer in the range (-prime/2, prime/2) which is
    equivalent to val modulo prime.
    """
    if prime is None:
        return val
    half_prime = prime // 2
    return ((val + half_prime) % prime) - half_prime