Renderingen-US

conversio-functio

Translation status: English reader-locale proof. Term names and code fences follow the en pack; supporting prose may still be English.

A registered @ conversion function also serves an explicit ↦ between its two types.

Syntax: @ conversion fn f(A a) → B [⇥ E] { … } … a ↦ B [⊥ <default>]

Category#

conversion

Examples#

radix/corpus/conversio/conversio-functio.fab (canonical · conversio)#

A registered @ conversion function also serves an explicit ↦ between its two types.

# =============================================================================
# conversio-functio — A registered conversion function serves an explicit ↦.
# =============================================================================
#
# What this teaches:
#   • `@ conversion` on a top-level function registers its (parameter type,
#     return type) pair. `a ↦ B` between those two types calls it.
#   • Only direct pairs convert: A ↦ B and B ↦ C never compose into A ↦ C.
#   • A function that declares `⇥ E` makes `↦` failable: write a `⊥`
#     default, or let the failure propagate from a function with a channel.
#
# Common mistakes:
#   • Writing the conversion inside the type — conversions are top-level
#     `@ conversion` functions, never members of a class or union.
#
# See also: ↦, ⊥, ⇥
# =============================================================================

class Celsius {
    var float degrees
}

class Fahrenheit {
    var float degrees
}

class Reading {
    var int value
}

class Gauged {
    var int value
}

@ conversion
fn toFahrenheit(Celsius c) → Fahrenheit {
    return Fahrenheit { degrees = c.degrees * 9.0 / 5.0 + 32.0 }
}

# A failable conversion: a negative reading has no gauge value.
@ conversion
fn toGauged(Reading r) → Gauged ⇥ string {
    if r.value ≺ 0 {
        throw "negative reading"
    }
    return Gauged { value = r.value }
}

main {
    # infallible: ↦ calls toFahrenheit
    const Fahrenheit boiling ← Celsius { degrees = 100.0 } ↦ Fahrenheit
    print boiling.degrees

    # failable: the ⊥ default applies only when toGauged fails
    const Gauged kept ← Reading { value = 7 } ↦ Gauged ⊥ Gauged { value = 0 }
    print kept.value
    const Gauged fallback ← Reading { value = -4 } ↦ Gauged ⊥ Gauged { value = 0 }
    print fallback.value
}

Expected output:

212.0
7
0