aboutsummaryrefslogtreecommitdiff
path: root/docs/langs.md
diff options
context:
space:
mode:
authorBruce Hill <bruce@bruce-hill.com>2025-03-10 12:42:45 -0400
committerBruce Hill <bruce@bruce-hill.com>2025-03-10 12:42:45 -0400
commit39dd1ca27da9e9d88ee59565df99ee281e1b3632 (patch)
tree107558459d134c052e5e912dceca03d0a0c26aa3 /docs/langs.md
parent806e0d0554a8f619cb5b835e535f5f1022543c1a (diff)
Add `convert` keyword for defining conversions
Diffstat (limited to 'docs/langs.md')
-rw-r--r--docs/langs.md23
1 files changed, 21 insertions, 2 deletions
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({
$/&/ = "&amp;",
$/</ = "&lt;",
@@ -74,7 +74,7 @@ instead of building a global function called `execute()` that takes a
```tomo
lang Sh:
- func Sh(text:Text -> 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])
+```