Pointers in Elm
import Html exposing (text)
-- We'll show how references work in contrast to values with
-- 2 functions: `zeroval` and `zeroptr`. `zeroval` takes an
-- `Int` parameter, so arguments will be passed to it by
-- value. `zeroval` will get a copy of `ival` distinct
-- from the one in the calling function.
zeroval : Int -> Int
zeroval ival =
0
-- Elm doesn't have pointers, so we'll simulate the behavior
-- of `zeroptr` using a tuple. The first element of the tuple
-- will represent the "pointer" (which is just the value itself in Elm),
-- and the second element will be a function to update that value.
zeroptr : (Int, Int -> Int) -> (Int, Int -> Int)
zeroptr (iptr, updater) =
(0, updater)
main =
let
i = 1
_ = Debug.log "initial:" i
-- Call zeroval
_ = zeroval i
_ = Debug.log "zeroval:" i
-- Simulate calling zeroptr
(newI, _) = zeroptr (i, \_ -> 0)
_ = Debug.log "zeroptr:" newI
-- In Elm, we don't have pointers, so we'll just log the value
_ = Debug.log "value:" i
in
text "Check the console for output"
Elm is a functional programming language that runs in the browser, so it doesn’t have the concept of pointers like Go does. Instead, we’ve simulated the behavior using pure functions and tuples.
In this Elm version:
We define
zeroval
as a function that takes anInt
and always returns0
. This is similar to the Go version, but in Elm, we can’t modify the input parameter.Since Elm doesn’t have pointers, we simulate
zeroptr
using a tuple. The first element of the tuple represents the “pointed-to” value, and the second element is a function that updates this value.In the
main
function, we useDebug.log
to print values to the console, simulating thefmt.Println
calls in the Go version.We call
zeroval
withi
, but since Elm is immutable, this doesn’t change the originali
.We simulate calling
zeroptr
by using our tuple-based version and then logging the new value.Instead of printing a pointer address (which doesn’t exist in Elm), we just log the value of
i
.
To run this Elm program, you would typically compile it to JavaScript and run it in a browser. The output would appear in the browser’s console:
initial: 1
zeroval: 1
zeroptr: 0
value: 1
Note that in Elm, all data is immutable, so we can’t directly modify variables as we do in Go. Instead, we return new values from our functions. This is a fundamental difference between Elm (a purely functional language) and Go (an imperative language with some functional features).