From 39dd1ca27da9e9d88ee59565df99ee281e1b3632 Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Mon, 10 Mar 2025 12:42:45 -0400 Subject: Add `convert` keyword for defining conversions --- docs/langs.md | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/langs.md b/docs/langs.md index ed5e3496..f087b31c 100644 --- a/docs/langs.md +++ b/docs/langs.md @@ -10,7 +10,7 @@ where a different type of string is needed. ```tomo lang HTML: - func HTML(t:Text -> HTML): + convert(t:Text -> HTML): t = t:replace_all({ $/&/ = "&", $/ Sh): + convert(text:Text -> Sh): return Sh.without_escaping("'" ++ text:replace($/'/, "''") ++ "'") func execute(sh:Sh -> Text): @@ -84,3 +84,22 @@ dir := ask("List which dir? ") cmd := $Sh@(ls -l @dir) result := cmd:execute() ``` + +## Conversions + +You can define your own rules for converting between types using the `convert` +keyword. Conversions can be defined either inside of the language's block, +another type's block or at the top level. + +```tomo +lang Sh: + convert(text:Text -> Sh): + return Sh.without_escaping("'" ++ text:replace($/'/, "''") ++ "'") + +struct Foo(x,y:Int): + convert(f:Foo -> Sh): + return Sh.without_escaping("$(f.x),$(f.y)") + +convert(texts:[Text] -> Sh): + return $Sh" ":join([Sh(t) for t in texts]) +``` -- cgit v1.2.3