aboutsummaryrefslogtreecommitdiff
path: root/src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks
diff options
context:
space:
mode:
Diffstat (limited to 'src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks')
-rw-r--r--src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/code.gleam18
-rw-r--r--src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/text.html13
2 files changed, 31 insertions, 0 deletions
diff --git a/src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/code.gleam b/src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/code.gleam
new file mode 100644
index 0000000..a97b8fc
--- /dev/null
+++ b/src/content/chapter5_advanced_features/lesson06_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/lesson06_external_gleam_fallbacks/text.html b/src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/text.html
new file mode 100644
index 0000000..243c7ea
--- /dev/null
+++ b/src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/text.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>