aboutsummaryrefslogtreecommitdiff
path: root/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2024-03-26 13:57:31 +0000
committerLouis Pilfold <louis@lpil.uk>2024-03-26 13:57:31 +0000
commitc2dcbe0f25a3e8bd60a4ccf377bbdd47f4794871 (patch)
tree18862644ee2dada0a926392b11e606bb0d2262f7 /src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks
parentccf75d2c362ac8e4dcd12c781f6e1eafd0064813 (diff)
downloadtour-c2dcbe0f25a3e8bd60a4ccf377bbdd47f4794871.tar.gz
tour-c2dcbe0f25a3e8bd60a4ccf377bbdd47f4794871.zip
Document opaque types
Closes https://github.com/gleam-lang/language-tour/issues/63
Diffstat (limited to 'src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks')
-rw-r--r--src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/code.gleam18
-rw-r--r--src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/en.html13
2 files changed, 31 insertions, 0 deletions
diff --git a/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/code.gleam b/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/code.gleam
new file mode 100644
index 0000000..a97b8fc
--- /dev/null
+++ b/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/code.gleam
@@ -0,0 +1,18 @@
+import gleam/io
+
+@external(erlang, "lists", "reverse")
+pub fn reverse_list(items: List(e)) -> List(e) {
+ tail_recursive_reverse(items, [])
+}
+
+fn tail_recursive_reverse(items: List(e), reversed: List(e)) -> List(e) {
+ case items {
+ [] -> reversed
+ [first, ..rest] -> tail_recursive_reverse(rest, [first, ..reversed])
+ }
+}
+
+pub fn main() {
+ io.debug(reverse_list([1, 2, 3, 4, 5]))
+ io.debug(reverse_list(["a", "b", "c", "d", "e"]))
+}
diff --git a/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/en.html b/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/en.html
new file mode 100644
index 0000000..243c7ea
--- /dev/null
+++ b/src/content/chapter5_advanced_features/lesson08_external_gleam_fallbacks/en.html
@@ -0,0 +1,13 @@
+<p>
+ It's possible for a function to have both a Gleam implementation and an
+ external implementation. If there exists an external implementation for the
+ currently compiled-for target then it will be used, otherwise the Gleam
+ implementation is used.
+</p>
+<p>
+ This may be useful if you have a function that can be implemented in Gleam,
+ but there is an optimised implementation that can be used for one target. For
+ example, the Erlang virtual machine has a built-in list reverse function that
+ is implemented in native code. The code here uses this implementation when
+ running on Erlang, as it is then available.
+</p>