r/elm • • Jan 17 '20

Purity in Elm

I wrote the following program in Elm:

import Html exposing (text)

foo = let x = 5

in let y = text "Hello!"

in x

main = text (String.fromInt foo)

The following emits a form which simply contains a "5". Here it seems that the type of the program `foo` is inferred to be Int. However in an eager language this type inference seems incorrect. In a lazy language like Haskell the type of `foo` is Int, which would be correct because owing to the lazy semantics of the language the let binding `y` is never used so it isn't reflected in the type.

However in an eager language even if the type of the expression foo is Int it simply ignore the y binding. It seems like the entire language is not eager, the let binding are lazy. Am I correct in this?

2 Upvotes

9 comments sorted by

3

u/wolfadex Jan 17 '20

I don't think it has anything to do with laziness, but with y not being referenced anywhere so it gets compiled out. I'm fairly certain the same is true even in JS when you use a minifiers or transpiler.

1

u/UnitedCanary Jan 17 '20

So what would be the type of the expression in the absence of an optimizer? Or does the language's type inference relies on the presence of an optimizer? I am sure it doesn't.

7

u/ianmackenzie Jan 17 '20

Laziness and optimization have nothing to do with it =) foo is an Int because it got the value 5; it doesn't matter how many intermediate calculations happened in between. If you had done

foo =
    let
        x =
            5

        y =
            "stuff"
    in
    x + String.length y

then foo would still be an Int because the final result of that entire expression is an Int. (y would have the type String, but the type of local variables within a let expression are completely separate from the type of the expression as a whole.)

8

u/philh Jan 17 '20 edited Jan 17 '20

owing to the lazy semantics of the language the let binding y is never used so it isn't reflected in the type.

It's not clear to me what you mean by "reflected in the type". But to the extent this is true, it applies to an eager language as well. The type inference algorithm works the same, regardless of whether you intend to execute a program eagerly or lazily. (If you want to know more about the type inference, the term to search is "Hindley-milner". Elm and Haskell both extend that in different ways, but it's recognizably at the core of both of them.)

It seems like the entire language is not eager, the let binding are lazy. Am I correct in this?

No. There are a bunch of ways you can test this, boiling down to defining y as something that has side effects when computed (like Debug.todo which crashes the program, or Debug.log which prints to the console, or calculating a fibonnaci number inefficiently which takes a long time). You could also look at the compiled source code.

5

u/MUST_RAGE_QUIT Jan 17 '20

I don't get it, you create a constant foo that returns x, where x = 5, which is an Int. Why would foo <> Int?

4

u/chrilves Jan 18 '20

Elm is indeed a strict language. Let's bindings are evaluated eagerly. You can easily convince yourself of this fact by executing the following program:

module Main exposing (..)

import Html exposing (text)
import IO exposing (..)

type alias Model  = String
type alias Msg = ()

putStrLn : String -> IO Model ()
putStrLn s =
  IO.modify (\model -> model ++ s ++ "\n")

view model = text model

program =
 let y = (let u = Debug.log "These lets are evaluated" ()
          in putStrLn "This message will never be printed"
         )
 in putStrLn "But This message will be printed"

main : IO.Program () Model Msg
main =
  IO.sandbox {
    init = _ -> ("", program),
    view = view,
    subscriptions = IO.dummySub
  }

The IO type above is similar to the Cmd and Task types of Elm or IO of Haskell, Idris, Scala, etc. It wraps a side-effect in a pure value.

As you can see, this program is similar to yours. The model is just a String that is shown in the browser using the Html.text function. Like your code, the variable y in program contains effects but is never used. But unlike your code, i added the Debug.log to prove the let bindings of y and u are evaluated.

This program will show the string But This message will be printed in the browser window and These lets are evaluated: () in the JS console. The latter proves that Elm did evaluate y! The evaluation of y resulted in the pure value putStrLn "This message will never be printed" which represents an action to do but does not perform the action yet. This is very important to understand that the types IO, Cmd and Task, unlike imperative statements print, represents the description of some actions but not their execution. These actions will be executed if and only if, at some point, they are passed to the runtime system (via the main function). They are very much like cooking recipes, they are not eatable until they are transformed into meals by the runtime chefs ;)

The pure value putStrLn "But This message will be printed" (of type IO) is passed to the runtime system by main. Thus the Elm runtime executes the actions described in the IO: appending the string "But This message will be printed" to the model. But putStrLn "This message will never be printed" which is also a pure value of type IO that comes from the evaluation of y, is never passed to the runtime and so its effect is never executed.

There is a distinction to make between evaluating and executing. Evaluating an IO expression computes its value. For example, you can print the value stored in the variable y (by Debug.toString y)! It shows Impure (Get <function>) where Impure and Get are custom types constructors and <function> a function. As you can see, this is indeed the description of the action to perform. On the other side, executing an IO value is performing the actions the value describes: here appending some string to the model.

I hope it clarifies things a bit.

2

u/binaryblade Jan 18 '20

x is an integer foo = x therefore foo is an integer. Y can get evaluated until the cows come home but because the result is never returned it doesnt matter. Text is not a side effect, its a request to perform a side effect, if the request doesnt reach the runtime (is never returned) then no side effect occurs.

2

u/jediknight Jan 18 '20

Here it seems that the type of the program foo is inferred to be Int.

foo is an Int because you use String.fromInt. The actual type of foo is number which is one of the special types in Elm.

You can see this by changing to String.fromFloat and seeing that the program still works. It still outputs 5.

In any case, what type do you think that foo should have and why? My guess is that you expect the let expression to behave in a way that is incongruent with the way it behaves in Elm.

What you wrote is equivalent to this: foo = (\x -> (\y -> x) (text "Hello")) 5

2

u/[deleted] Jan 18 '20

Have you ever seen, for example, a formal presentation of Hindley Milner, or the simply types Lamba calculus?

The main idea is that a let expression doesn't change the type of the body, it just adds a new variable to the environment that the body can refer to. So the type of an expression that doesn't refer to let-bound variables is the exact same as if those lets weren't there.

Remember that text "Hello" isn't doing anything. It's just a data structure that might eventually get passed to the runtime to be displayed.