Implementing an equivalent for Haskell's `undefined` and lazy evaluation in Elm

667 views
Skip to first unread message

Noah Gordon

unread,
Nov 3, 2015, 1:49:17 PM11/3/15
to Elm Discuss
I know that Elm's Debug module has the `crash` method, which can be used to "stub" non-implemented patterns in a similar way to Haskell's `undefined`.

fn : Bool -> String
fn x
=
 
case x of
   
True -> "It's True!"
   
False -> crash "Undefined!"

fn
True  |> show  => "It's True"
fn
False |> show  => (raises error "Undefined!")

Cool! That works the way I want it to. It compiles, but raises an error in Javascript if the "crash" is ever invoked.

To make this sort of pattern a bit more concise, I wanted to implement the `undefined` method in a simple way.

undefined : a
undefined = crash "Undefined!"

However, when I use this function defined in the above example the Javascript seems to evaluate the crash for some reason.

fn : Bool -> String
fn x = 
  case x of
    True -> "It's True!"
    False -> undefined

fn True |> show  => (raises error "Undefined!")

Strangely, even defining the function `undefined` but not evaluating it anywhere in the main sequence causes the Javascript to crash after the compiler gives it an OK.

Can anyone shed some light on this situation? I understand that Elm cannot lazily evaluate code in the same way Haskell does because it compiles to Javascript, but it seems strange that simply defining the `undefined` function without invoking it causes an error. What am I not understanding about the way Elm evaluates functions and/or compiles to Javascript?

Joey Eremondi

unread,
Nov 3, 2015, 1:53:20 PM11/3/15
to elm-d...@googlegroups.com
Unlike Haskell, Elm is strict. What you're doing is defining a top-level constant called undefined. It compiles, and when you run your code, the Javascript evaluates each top level value. Most top-level values are functions, but this one is a value, meaning that the Javascript tries to evaluate it. Which, gives the crash.

The only way to do something like this in Elm is to wrap it up in a closure. So you can have something like this:
undefined : () -> a
undefined _ = crash "Undefined!"

But otherwise, every time you declare undefined, Elm will try to evaluate it fully, and cause the crash. The only thing that can delay evaluations in Elm is wrapping something in a lambda.

Hope this helps!

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Noah Gordon

unread,
Nov 3, 2015, 1:59:17 PM11/3/15
to Elm Discuss
Thanks, that's very helpful. The tricky part was understanding that top-level functions are compiled to constants. Now understood!
Reply all
Reply to author
Forward
0 new messages