diff options
author | Louis Pilfold <louis@lpil.uk> | 2024-01-18 17:47:12 +0000 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-01-18 17:47:12 +0000 |
commit | 3bfbe688f5a62e29835c7d3c4f282e7fff57949d (patch) | |
tree | 038cd1bf7a72949f7d68358ffd8af59d073ef70a /src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks | |
parent | f92661980deac22b54e79cd44c25caba17910c95 (diff) | |
download | tour-3bfbe688f5a62e29835c7d3c4f282e7fff57949d.tar.gz tour-3bfbe688f5a62e29835c7d3c4f282e7fff57949d.zip |
Rename
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.gleam | 18 | ||||
-rw-r--r-- | src/content/chapter5_advanced_features/lesson06_external_gleam_fallbacks/text.html | 13 |
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> |