Grain: A strongly-typed functional programming language for the modern web
grain-lang.org
grain-lang.org
Maybe show some examples of errors Grain would catch that JavaScript wouldn't, like Elm does: http://elm-lang.org/
Why? They all target browsers. What else would you compare it to?
The shiny new toy is wasm-bindgen (https://github.com/rustwasm/wasm-bindgen), which will soon allow the use of WebIDL (https://heycam.github.io/webidl/) to wrap the entire browser API, if I understand correctly.
In practice, it all seems to work pretty well. But for public-facing sites, you need to watch the number of dependencies you include and keep the *.wasm size down.
This ability is a tool and nothing precludes a wasm target for Elm (in fact Evan specifically expressed interest in it: https://github.com/WebAssembly/gc/pull/1#discussion_r1115011...).
Either way, comparing Grain to JS or Elm is anything but pointless, at the end of the day it's competing with them.
PureScript is a Haskell dialect that was built specifically to run on top of JavaScript engines. Specifically, compared with Haskell, it is strictly evaluated (whereas Haskell is non-strict / lazy, well almost). However it eliminates some of Haskell's baggage, but retains Haskell's functional purity.
It's all around an awesome programming language for FP that targets JavaScript engines, far surpassing any other attempt.
This is something I wonder about JS: there are a lot of places that exceptions happen in (say) Python that just return `NaN` or `undefined` in javascript. Is it intentional? Is it a good idea?
Examples: the multiplication operator essentially never throws. Out-of-bounds (or "not found") lookups don't throw.
I suspect the logic is "only throw if you have the wrong type for that operation" -- like calling something that isn't a function, or looking up an attribute on something that isn't an object. (Except multiplication for things that aren't numbers is fine, I guess...)
I'm writing a dynamically typed language and don't know if it's better to go the JS way or the Python way. Or do something horrible like having multiplication return a `Maybe` type...
Here's a little thought experiment: Your program ends up with an "undefined" in some variable 'x'. How did that happen? In JS it can happen in any number of weird and wonderful ways, e.g. you called a function which did a 'v[i]' or it could have just fallen off the end because someone forgot to check a return path, or...
In Python there's much less scope what the problem could be. Since v[i] will just throw an IndexError, you know that the problem couldn't possibly be stray index or similar.
That is a much better experience for finding problems in one's code.
The web powers through!
It has everything to do with sandboxing (or not). Ads being served by third parties should not be able to influence the JS running in the page.
Users generally ignore all messages coming from their computers. They routinely blame their computers for doing things that the computers are not doing at all. Like, oh I can’t find the document I wrote three weeks ago -> obviously my computer is being disobedient.
Anyway, I don’t blame the users. To them the computer is entirely uninteresting and they don’t want to care about the sorts of concerns that we technically minded people do.
A broken page is a broken page and it doesn’t matter to the user why the page is broken. The only thing that matters to them is, can they do the thing they wanted to do or not. And like the sibling said, the web browsers are surprisingly good at handling broken code.
"Order total: undefined" is hugely different from "There was an error -- maybe just leave the page, yeah?".
There’s an equivalence you can make between a type and a mathematical set, where you say that the type is the set of all possible values for that type.
In both JavaScript and math, multiplication of numbers is an operation that has a special property called closure, which means that the return type is the same as the input types. Multiply a number by another number and you will ALWAYS get a number back. The inputs and the outputs are in the same set, which means you can go nuts multiplying numbers and you’ll never have to check your values to make sure they’re still numbers; it can be safely assumed.
JavaScript gives NaN a type of “number” as a clever compromise. Instead of throwing an error when multiplying a number by a non-number, JS allows multiplication to still return a “number” (`4 * ‘a’ === NaN`) and then you don’t need to ever worry about accidentally “leaving” the set of numbers (`NaN * 10 === NaN`).
More likely than not though, multiplying a number and a string is just not a useful thing to do. With a good type system, a program that could wind up in a situation of multiplying a string and a number can be rejected by the compiler.
So in a roundabout answer to your question, a lot of “what then?!” situations can be entirely avoided with a good type system. For the remaining situations like accessing an element in an array that may not exist, a Maybe can make a lot of sense.
(Maybe Float turns out to be just like JavaScript’s numbers, but instead of NaN you have Nothing.)
Computer numbers in general have all sorts of issues like this where clean mathematical theory is broken. NaN, Infinity and -Infinity, for example, are all similar to absorbing elements[1] under multiplication in the sense that once you get that as a result, you can't do the inverse operation (division) to get back to your original inputs.
Compile time is better than runtime, evaluation time is better than via explicit value inspection.
Non-signalling NaNs provide an easy way of distributing an invalid value widely throughout a program's data structures before it's discovered.
The only reason to go the other way, and have silent NaN propagation, is if they're expected to occur very frequently. For example, consider how awkward SQL would be if evaluating over null values triggered errors - the conditionality of expressions would need to become very elaborate.
Monadic approaches to errors (Maybe, Rust's Result, that conditionally apply a function to a value only if it's not an error) blur the line between these two. Because they rely on data flow, they feel a bit like non-signalling NaNs. OTOH, evaluation generally bubbles up using monadic return types, and errors bubble up too, just like exceptions - exceptions, and consistent, universal use of monadic return types, are isomorphic and can have the same evaluation characteristics.
I feel like there is a small but important difference. Encoding exceptions in monadic return types allows the type system to guarantee that all exceptions are handled, or at least considered by the programmer. That is a very strong guarantee, especially as you put up layers and layers of foreign libraries and abstractions.
Yes and no respectively.
It's intentional in the sense that the original Javascript was not intended to fault (much) because it was for basic scripting, so if one small script blew up it should not bring down the entire page's scripting. This also resulted in Javascript's exceptions facilities being very shitty (exception handling is not very flexible/convenient, and while that may have changed since — not sure — for a long time it was impossible to sub-type the native Error).
However it's not really a good idea for non-trivial software systems, it makes errors much harder to notice, recover from and debug. In fact "modern" JS APIs tend to fault e.g. parsing invalid JSON raises SyntaxError, it doesn't return null or undefined; and promises and async functions will convert exceptions to failures.
One thing I think I like about JS over Python is that empty containers are "truthy". This, combined with non-raising missed lookups, tends to be pretty ergonomic. For me, at least.
Though it is messier -- in Python `key in d` is well entrenched as an idiom, and in JS `if(d.key)` misfires if the value is zero, and `if(d.key === undefined)` doesn't discriminate between a missed lookup and a stored `undefined`. Though the latter must be discouraged, right?
PHP's json_decode does that. And yes `null` is also returned as a PHP NULL.
> Though it is messier -- in Python `key in d` is well entrenched as an idiom, and in JS `if(d.key)` misfires if the value is zero
Or false, or null, or the empty string, or NaN.
FWIW `if (key in d)` also works in JS if d is a native object, though you need `d.has(key)` if d is an actual Map object instead.
In practice that causes the output of your program be either Infinity or NaN but the problem is that is usually never what you want.
Then you want to know "Why do I get a NaN here?" and you will have to study all of your program and single step its execution to understand why you got an answer you din't want which is of little value to anybody.
Problem with Infinity is you can not come back from there. It does not cancel out if you subtract it.
Instead IN PRACTICE it is much better to catch errors early with the help of the type-system, unit-tests, and assertions.
It is an interesting challenge: How do I define the type "Any number except zero" and have my type-system then catch divisions by zero?
This wasn't javascript's idea. They're just following the spec. https://en.wikipedia.org/wiki/IEEE_754#Exception_handling
As John Carmack said: "...if you have a large enough codebase, any class of error that is syntactically legal probably exists there."
https://en.wikipedia.org/wiki/NaN
The purpose of silent propagation is for the expression to be checked at the end of the overall expression rather then have every operation itself be checked. It's a speed optimization. It is by far more user friendly for an invalid operation to throw an error.
For example
for this following operation
(100/2/2/0/2)
without NaNs the system must check 4 operations 100/2, 50/2, 25/2, 12.5/0 for an error. Every arithmetic operation whether it has a division by zero or not will have to have additional checks.
With NaNs the computer just runs through the entire operation with no checks and the user just explicitly does a check for a single NaN at the end. The Maybe Monad operates under the same concept when used as an output type for a division operation.
The same logic applies for javascript "undefined".
https://github.com/grain-lang/grain/blob/master/src/grain-st...
Or they don't support indexing at all.
I'm curious how they handle JSON parsing. For example in Scala/Play you define the class you want to parse to, and if the JSON passed in at runtime doesn't match the shape of that class then you get a runtime exception. Obviously it'd be nice if that didn't happen, but I can't think of any alternative that would make sense.
In more detail:
It's purely functional, so it cannot handle I/O at all on its own. It needs some sort of harness into which it fits which handles that, and which then calls the pure functions in Elm / Grain. In Elm's case that harness is JavaScript, and it seems to be a similar case for Grain. (Maybe for Grain it's WebAssembly? I don't honestly know enough about Web Dev to say).
During I/O (including user input, and sending data over a network), runtime exceptions can still be thrown, but once it's been converted and passed into the functional part, it's in a sense correctly formatted by definition, and the purely functional Elm / Grain parts don't throw runtime exceptions at all.
Returning a sum of success + error, as e.g. Rust's Serde[0] or Elm's Json.Decode[1] do.
The developer gets the feedback that the operation has failed at runtime, but they also get the feedback that the operation can fail and they must handle it somehow at compile-time, even ignoring the issue is an explicit decision.
[0] https://docs.serde.rs/serde_json/de/fn.from_str.html
[1] http://package.elm-lang.org/packages/elm-lang/core/latest/Js...
In Play this is actually something like JsSuccess/JsError, not an exception, although Play is pragmatic (aka dirty) at times, so it's possible that it has functions throwing exceptions.
> No runtime exceptions, ever. Every bit of Grain you write is thoroughly sifted for type errors, with no need for any type annotations.
That's... weird to me. That seems to posit that ALL runtime exceptions are necessarily type errors. Huh?
What about full disk, DB errors, data verification error, parsing errors, network errors, and tons of other errors that don't appear to be type system related?
[A] This language only doesn't realize this class of errors exist, which, um, seriously? That can't bode well.
[B] The language uses the type system to propagate such errors. `Either<Result, ErrorCode>` for example. The language is somewhat unique in that it is designed to enforce such code style for ALL possible error conditions.
[C] The language returns null or blank objects on error conditions, such as how (early) javascript returns 'NaN' when trying to parse "hello!" as a number, instead of raising an error condition. That's a style choice I really wouldn't like, but I guess to each their own.
(There are of course also true runtime errors -- e.g. out-of-memory -- and precondition errors -- i.e., coding errors that fall outside the capability of the type system to enforce -- which do not fit this pattern.)
...
> Erlang for example follows that pattern.
Erlang is its own beast; if you characterize pattern matching as part of a type system, which I guess it is, then...maybe if you squint?
Normal errors are indeed typically reflected in the return value, but if the error pattern doesn't match the code's expectations then a runtime exception is thrown...if you're lucky. If the error pattern happens to fit with the pattern match but the code doesn't know about it, eventually some other error will occur.
Anyway, Erlang definitely doesn't fall into the "No runtime exceptions, ever" category, and as such doesn't really fit with the options the OP presented.
With a sufficiently complete static (even inferred) type system, you can catch any possibility of such failures AOT and not run into any error patterns that don't match code expectations at runtime, so while the description isn't literally true of Erlang, Erlang does show a way that it could be true of a language with AOT enforcement of adequate type system.
Erlang absolutely has a concept of exceptions. They're even called exceptions: http://erlang.org/doc/reference_manual/errors.html#exception....
{ok, Result} = foo()
though, and that raises badmatch if it fails, and you handle it in a supervisor.The basic tradeoff is, most program can't (or don't) handle an "out-of-memory" error anyways, so for those, "nothrow" and "nothrow+allocates" is essentially the same. On the other hand, some (few) software is written to handle "out-of-memory" errors, and C++ is one of the few languages that targets such software, so in those programs, the distinction is meaningful.
A harder problem is errors that cannot be handled by a simpler type system. For example, consider Haskell's head function, which is defined like this:
head :: [a] -> a
In other words, it takes a list, and returns the first element. But if the list is empty, it throws an exception (technically called an "error" in Haskell): > head []
*** Exception: Prelude.head: empty list
Haskell's type system is extremely powerful, but it cannot catch this at compile time.In order to express constraints such as "list must not be empty" or "number must be higher than 1" or "file must be open, the type system needs to understand the semantics of the values expressed by a type system. This can be solved by dependent typing, but that's a complicated concept currently implemented by only a handful of languages (e.g. Idris).
dependant typing isn't needed for some use cases you have mentioned:
> list must not be empty you can use NonEmpty
https://hackage.haskell.org/package/base-4.9.0.0/docs/Data-L... . We are still encoding this special case and our intent in types. Cons is that we need a special support for it (special library) where with dependant types we could reason about this use case without a special library
EDIT: added newlines
Mostly because Go is terrible.
> Haskell's type system is extremely powerful, but it cannot catch this at compile time.
The problem is not the type system, it's that Haskell's error handling is inconsistent.
Elm, despite having a much simpler type system than Haskell, handles this properly:
head : List a -> Maybe a
This has nothing to do with the type system itself and everything to do with how the type system is used (or not used). The designers of Haskell's `head` decided to make it a partial function, leading to type-checking inputs not generating any output.Making them total makes them a bit heavier for the best case, and furthermore can seem unnecessary (as you could just pattern-match the list itself).
You can also see this oddity in Haskell allowing non-exhaustive case, and allowing refutable patterns in bindings.
listToMaybe :: [a] -> Maybe a
(http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-M...)Haskell's head function is often pointed to as a wart even given Haskell's type system; the signature really ought to be:
head :: [a] -> Maybe a
With a definition (equivalent to): head [] = None
head x:xs = Some x
It's absolutely not a good example of a source of errors that can't be dealt with in a type system like Haskell's.> In order to express constraints such as "list must not be empty" or "number must be higher than 1" or "file must be open, the type system needs to understand the semantics of the values expressed by a type system.
Sure, but you don't have to express those as type constraints to avoid runtime errors when they occur; if you can express the distinction in normal code you can use distinctions of return type.
Grain is definitely still really in its alpha form. There's lots we want to do with it that we're still getting around to! We weren't quite expecting much of any traffic to the site, but that's really my fault for having the site be public before we were at least a bit further along. :)
Even still, it's been awesome to get a lot of early feedback! We'll get a roadmap together so it's easier for people to see where we're trying to take the language.
I’m sure they’re open and would be happy to see contributions.
Translating source code into docs is a great way to learn and it looks like very pleasant language to read.
In this case, publicising, and getting more contributors can help fix these problems.
Taken to an extreme, it feels like reading a dynamically-typed language where you have to keep the various variable types in your head when debugging.
There's a middle ground.
There's a reason you still at least annotate the top level in Haskell, Elm, and friends even though the compiler could've inferred it. It's because humans have to read it.
https://github.com/grain-lang/grain/blob/master/runtime/src/...
A lot of new languages start out this way, where they just assume memory is infinite and then eventually add the GC later. That's a really nasty ball of technical debt to be sitting on, and I've seen nascent language implementations die because they couldn't get past it.
I see compiling to WASM as the key differentiator now. This likely means that all the mechanics required for an ML-style language, like garbage collection, must be included in a runtime library.
>>> there's already a very efficient, solidly tested, constantly improving garbage collector in your browser that uses all the possible dirty low-level tricks known to mankind, which is the GC being used for JavaScript. What if we could give you access to the garbage collector directly?
https://blog.benj.me/2018/07/04/mozilla-2018-faster-calls-an...
It is merely calling a function within another function. I would expect the second function to take in first function as a parameter (which JavaScript already has).
Leaving the marketing efforts aside, what people want to express is "statically typed". A static type system can prove a lot of things about your program. Traditionally you could rely on (good) static type system to prove that your program is memory safe, or that it has as few runtime errors as possible, preferably zero. N.B. don't fall into the trap of saying that a language like C is statically typed. When you can pass void pointers around and cast that to anything, that's in fact not static typing.
Type theory has a lot to do with math logic actually, the two being highly interchangeable. Statically typed compilers can prove various properties about your program, freeing the developer from writing certain classes of tests, plus it makes refactoring easier.
Refactoring, correctness, these are things people have always struggled with in JavaScript, especially due to JavaScript's nature. Quick, can you tell me the answer to "Math.min() < Math.max()" in JavaScript?
You know it's a trick question, given this is JavaScript, don't you ;-)
---
Other than ClojureScript, I don't know of any other dynamic language targeting JavaScript engines and that's interesting. None. And ClojureScript is only interesting because it is a LISP and because it has sane conventions and defaults.
Languages providing superficial syntactic sugar, such as CoffeeScript, have been a really bad idea and I'm glad that we've moved on.
Therefore the innovation that happens tends to happen in statically typed languages, because there's a lot there left to explore and because such languages tend to bring value.
That said I always wonder what new languages bring to the table versus already available alternatives like PureScript, Scala.js, ClojureScript, Elm, etc. And from the TFA I don't understand what those advantages are.
Static-typing, immutable datastructures, FP... these are things that even the Javascript ecosystem has been moving towards with React, Typescript, Redux, and more.
If you're making a language for the browser, you can offer a lot of value by rolling these into a single tool. For example, it may be much simpler for you to use Elm than to approximate Elm with your own menagerie of JS tools.
[0] it's not very useful either if you have pattern matching on lists, you can just match the list directly.
event click $(table > thead > tr > th) {
// click on table header cell
// 'this' is that th element
}
class Widget : Element
{
function attached() {...}
event click $(span.up) { this.increment(); }
event click $(span.down) { this.decrement(); }
event mousedown { this.state.focus = true; }
...
}I haven't done any web development to speak of, but I've done a fair bit of GUI stuff, doing things like this snippet appears to in languages that don't have "events" as a separate category of thing.
observable.on("click", observerFunc);
// or observable.addEventListener(...);
is an executable statement. And this class Widget : Element {
event click { … observer's code … }
}
is a declaration.That executable statement needs to be called at some point of time. So the observable can be in two states - with and without that event handler.
While class declaration is an invariant (at least in Sciter) - as soon as element is in DOM it has that class and consistent set of event handlers in place. Such binding is done by, again, CSS declaration:
widget {
prototype: Widget url(path); // <widget> controller
display: block;
...
}
"I've done a fair bit of GUI stuff"AFAIR VB6 and Delphi allow to declare event handlers without explicit/runtime binding - that's close as a concept to the above.
let f x = if (x == 0) then 0 else (f x)Considering ongoing efforts to create a WebAssembly backend for OCaml (and thus Reason), I wonder what would be the selling point of Grain.
Aside from the wasm compilation, I don't see why this exists.
I went back and checked, and Grain not only takes OCaml's code without clear attribution but redistributes that code under GPLv3 where the original code is under LGPLv2.1. That's bad.
I can see, though, that wasm might encourage experimentation by a wider group of people who are put off by targetting js.
Coming back to Elm, it'd be great to see others consider the wider architectural questions. The Elm architecture and language are beautifully complementary. That's stark when looking at react - which was copied from (or at least inspired by) the Elm architecture. However, being js-based, it doesn't have the mutual consistency of elm - and so has to resort to syntactic gymnastics.
Anyway, that's getting off topic. Grain is clearly early stage. Anyone motivated enough to conceive and deliver a language deserves some encouragement. Will be interesting to see how it evolves.
List<Animal> animals = [Dog()];
List<Cat> cats = animals;
What is a static type system worth if it doesn't catch type errors at compile time?A note to language designers: I can understand the { } but if you use them why do you also need the ( ) around the conditionals here?
if (n <= 1) {
n == 0
} else {
isOdd(n - 1)
}
The parser can find where the condition starts (after the if) and ends (at the {) and we won't have to type two useless characters. It's ergonomics. static function isEven(n)
return if (n <= 1)
n == 0;
else
isOdd(n - 1);
static function isOdd(n)
return if (n <= 1)
n == 1;
else
isEven(n - 1);
i.e. An if expression consists of other expressions that may or may not be a block expression ({ }).Python ends if lines with a : which might help the parser, but maybe not because it was a late addition to help readability. For me it adds work when moving code around because I have to add or remove the :
Ruby does totally without any terminator in that context (in other contexts it has its own {} or do...end). The parser keeps processing successive lines until it understands that what follows can't belong to the conditional. I prefer that approach because it's the language/compiler that has to help me, not the other way around.
But how's that possible in general? Example, JSON parsing of data from a HTTP request. This is pseudo code
# request.data is
# {"a":1, "b":2, "c":"a string"}
data = parse(request.data)
total = data["a"] + data["b"] # 3
total = total + data["c"] # ops!
The last line is either a compiler error (how? forbidding input is not an option) or a runtime error (Grain doesn't have that) or what?Sign me up :)