Question about generated JavaScript code

If we have a file named Some.purs which contains the following code:

module Some where

class Foo a where
  bar :: a -> a

data Baz = Baz

instance fooBaz :: Foo Baz where
  bar _ = Baz

bat = bar Baz

Running this file through purs compile produces the following JavaScript:

// Generated by purs version 0.13.6
"use strict";
var Baz = (function () {
    function Baz() {

    Baz.value = new Baz();
    return Baz;
var Foo = function (bar) { = bar;
var fooBaz = new Foo(function (v) {
    return Baz.value;
var bar = function (dict) {
var bat = bar(fooBaz)(Baz.value);
module.exports = {
    bar: bar,
    Foo: Foo,
    Baz: Baz,
    bat: bat,
    fooBaz: fooBaz

Why is var bat = bar(fooBaz)(Baz.value) used instead of var bat = The only explanation that I can come with is that instances of typeclasses are internally represented as parameters to functions.

Note: couldn’t transforming instances of typeclasses this way be a good optimization?

You are correct that typeclasses (where you see => in type signatures) are an extra argument that the compiler implicitly fills in with instance dictionaries. This optimization would be taken care of by a very basic, general inliner over corefn. I wouldn’t recommend implementing a special purpose optimization just for calling class methods.

Thanks for answering! If you wouldn’t mind, I also have another question.

This PureScript code:

foo = if "bar" == "baz" then "Impossible!" else "Bingo!"

generates this JavaScript:

var foo = (function () {
    var $4 = "bar" === "baz";
    if ($4) {
        return "Impossible!";
    return "Bingo!";

Why doesn’t it use ternary operators like this:

var foo = "bar" === "baz" ? "Impossible!" : "Bingo!";

If/then/else is desugared to a case expression, which is codegenerated in a uniform way. I would expect JIT engines to optimize this away, though it is indeed more code.

UglifyJS also minifies it to a ternary operator, so I think it’s fine :slight_smile:

Anyway, thanks for answering my (probably silly) questions!