conversio-functio
Translation status: Tiếng Việt reader-locale proof. Term names and code fences follow the vi pack; supporting prose may still be English.
A registered @ chuyển function also serves an explicit ↦ between its two types.
Syntax: @ chuyển fn f(A a) → B [⇥ E] { … } … a ↦ B [⊥ <default>]
Category#
conversion
Related#
- ↦
- ⊥
- ⇥
Examples#
radix/corpus/conversio/conversio-functio.fab (canonical · conversio)#
A registered @ chuyển function also serves an explicit ↦ between its two types.
# =============================================================================
# conversio-functio — A registered chuyển function serves an explicit ↦.
# =============================================================================
#
# What this teaches:
# • `@ chuyển` 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 chuyển inside the type — conversions are top-level
# `@ chuyển` 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
}
@ chuyển
fn toFahrenheit(Celsius c) → Fahrenheit {
return Fahrenheit { degrees = c.degrees * 9.0 / 5.0 + 32.0 }
}
# A failable chuyển: a negative reading has no gauge value.
@ chuyển
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