@@ -3,879 +3,15 @@ purescript
4[](http://travis-ci.org/paf31/purescript)
4[](http://travis-ci.org/paf31/purescript)
6−A small strongly, statically typed compile-to-JS language with basic extensible records and type-safe blocks
6+PureScript is a small strongly, statically typed programming language with expressive types, written in and inspired by Haskell, and compiling to Javascript.
8Bitcoin donations are gratefully accepted at 14ZhCym28WDuFhocP44tU1dBpCzjX1DvhF.
8Bitcoin donations are gratefully accepted at 14ZhCym28WDuFhocP44tU1dBpCzjX1DvhF.
10−## Current Features
10+## Resources
12−- Full Type Inference
12+- [Documentation](http://purescript.readthedocs.org/)
13−- Higher Kinded Polymorphism
13+- [#purescript IRC @ FreeNode](irc://irc.freenode.net/#purescript)
14−- Support for basic Javascript types
14+- [Twitter](http://twitter.com/purescript)
15−- Extensible records
15+- [Try PureScript!](http://tryps.functorial.com/)
16−- Type-safe blocks with for/while/assignment etc.
16+- [Release Notes](https://github.com/paf31/purescript/blob/master/RELEASE.md)
17−- Functions with multiple arguments
17+- [Contributing to PureScript](https://github.com/paf31/purescript/blob/master/CONTRIBUTING.md)
23−- Optional tail-call elimination
28−Try PureScript in the browser [here](http://tryps.functorial.com/).
32−See the `LICENSE` file
36−Contributions are always encouraged! Please see `CONTRIBUTING.md` for guidelines.
38−- Join the discussion on FreeNode at <a href="irc://irc.freenode.net/#purescript">#purescript</a>.
39−- Follow @purescript on Twitter for development updates
43−Install the Haskell Plaform, then `cabal install`
47−The `psc` executable takes a list of PureScript source files as arguments and by default writes out its errors or output to the console.
49−The following options are supported:
52− Read input from standard input instead of from files
55− Write the generated Javascript to the specified file
58− Write a list of foreign imports declarations to the specified file in addition to generating Javascript output
60− --runtime-type-checks
61− Generate simple runtime type checks for function arguments with simple types.
64− Perform tail-call elimination on the generated Javascript.
67− Do not include the Prelude in the generated Javascript.
70− Overload the `do` keyword to inline calls to `bind` for the `Eff` monad, to generate more efficient code.
73− Generate a call to `Main.main` after all other generated Javascript.
77−I was looking for a simple functional language which would compile to JavaScript and have the following characteristics:
79−- Generate simple readable Javascript
80−- Provide the ability to compile to tight loops if necessary
81−- Reasonable type system
82−- Ideally, written in a programming language I would enjoy working in
83−- Provides a simple interface to existing Javascript code
85−I didn't find exactly what I was looking for, so I wrote PureScript. It doesn't have everything right now, but it should serve as a simple core on which to develop new ideas.
87−PureScript is *not* designed to be a general-purpose programming language. The primary use case is as a generator for purely-functional core libraries, with the main application code written in another language.
89−PureScript can also be seen as a trade-off between a theoretically ideal language and one which generates reasonably high performance code.
93−As an introductory example, here is the usual "Hello World" written in PureScript:
100−main = trace "Hello, World!"
103−which compiles to the following Javascript, ignoring the Prelude:
108− var main = trace("Hello, World!");
110−})(Main = Main || {});
113−The following command will compile and execute the PureScript code above:
116−psc input.purs --run-main | nodejs
121−The following code defines a `Person` data type and a function to generate a string representation for a `Person`:
124−data Person = Person { name :: String, age :: Number }
126−foreign import numberToString :: Number -> String
128−showPerson :: Person -> String
129−showPerson (Person o) = o.name ++ ", aged " ++ numberToString(o.age)
132−Line by line, this reads as follows:
134−- `Person` is a data type with one constructor, also called `Person`
135− - The `Person` constructor takes an object with two properties, `name` which is a `String`, and `age` which is a `Number`
136−- The `numberToString` function is written in Javascript, and converts a `Number` to its `String` representation
137−- The `showPerson` function takes a `Person` and returns a `String`
138−- `showPerson` works by case analysis on its argument, first matching the constructor `Person` and then using string concatenation and object accessors to return its result.
140−The generated Javascript looks like this:
143−var Person = function (value) {
144− return { ctor: 'Person', value: value };
147−function showPerson(_1) {
148− if (_1.ctor === "Person") {
149− return _1.value.name + ", aged " + numberToString(_1.value.age);
151− throw "Failed pattern match";
158−The type system defines the following types:
165− - E.g. `[String]`, `[[Number]]`
167− - E.g. `{ foo :: String, bar :: Number }`
169− - E.g. `data Foo a = Foo | Bar String`
171− - E.g. `Number -> String`
172− - E.g. `(Number, Number) -> Number`
173− - Functions can have zero or more arguments
175− - E.g. `forall a. a -> a`
179−The three primitive types `String`, `Number` and `Boolean` correspond to their Javascript equivalents at runtime.
181−PureScript supports the same binary and unary operations on primitive types as Javascript, with the following exceptions:
183−- String concatenation is denoted `++` to differentiate it from numeric addition, `+`
184−- PureScript's `==` and `!=` correspond to Javascript's strong equality tests `===` and `!==`
190−str = "Hello, " ++ "World!"
196−PureScript arrays correspond to Javascript arrays at runtime, but all elements must have the same type.
198−Array literals look like Javascript array literals: `[1, 2, 3]`
200−Array elements can be read using array index notation `arr !! index`
204−PureScript records correspond to Javascript objects.
206−Record literals look like Javascript object literals: `{ foo: "Foo" }`
208−Properties can be read by using dot notation: `o.foo`
212−Tagged unions consist of one or more constructors, each of which takes zero or one arguments.
214−Tagged unions can only be created using their constructors, and deconstructed through pattern matching (see later).
219−data Foo a = Foo | Bar String
221−runFoo Foo = "It's a Foo"
222−runFoo (Bar s) = "It's a Bar. The string is " ++ s
224−test = runFoo Foo ++ runFoo (Bar "Test")
227−In the example, Foo is a tagged union type which has two constructors. It's first constructor `Foo` takes no argument, and it's second `Bar` takes one, which must be a String.
229−`runFoo` is an example of pattern matching on a tagged union type to discover its constructor, and the last line shows how `Foo`s are constructed.
233−Functions in PureScript can have zero or more arguments in general, just like in Javascript.
235−Functions are introduced by using a backslash followed by a list of argument names:
238−test1 = \a b -> a + b
241−which would correspond to the Javascript
245− return function (b) {
251−Multiple argument functions can be introduced by wrapping the arguments in parentheses, and separating them with commas:
254−test1 = \(a, b) -> a + b
260−function test1(a, b) {
265−In the case of a function with no arguments, the parentheses may be omitted, as follows:
271−which would correspond to the Javascript `function test2() { return 100; }`
273−Multiple-argument and single-argument syntax can be mixed, as follows:
276−test3 = \a (b, c) d -> a + b + c + d
283− return function (b, c) {
284− return function (d) {
285− return a + b + c + d;
291−Functions are applied by providing their arguments inside parentheses:
298−A special case is made in the case of functions with one argument. These functions can be applied without parentheses, and function application associates to the left:
301−-- has type Number -> Number -> Number -> Number
302−addThree = \a b c -> a + b + c
304−-- has type Number -> Number -> Number
307−-- has type Number -> Number
316−Expressions defined at the top level may have polymorphic types.
324−`identity` is inferred to have (polymorphic) type `forall t0. t0 -> t0`. This means that for any type `t0`, `identity` can be given a value of type `t0` and will give back a value of the same type.
326−A type annotation can also be provided:
329−identity :: forall a. a -> a
333−Functions may also be polymorphic in row types or type variables with other kinds (see "Kind System"):
336−addProps o = o.foo + o.bar
339−Here, `addProps` is inferred to have type `forall r. { foo :: Number, bar :: Number | r } -> Number`. That is, it can take any type which has properties `Foo` and `Bar`, and *any other record properties*.
341−So, the following compiles:
344−addProps { foo: 1, bar: 2, baz: 3 }
347−but the following does not:
353−since the `bar` property is missing.
355−Again, a type annotation can be provided if necessary.
359−It is also possible for the `forall` quantifier to appear on the left of a function arrow, inside types record fields and data constructors, and in type synonyms.
361−In most cases, a type annotation is necessary when using this feature.
363−As an example, we can pass a polymorphic function as an argument to another function:
366−poly :: (forall a. a -> a) -> Boolean
367−poly f = (f 0 < 1) == f true
370−Notice that the polymorphic function's type argument is instantiated to both `Number` and `Boolean`.
372−An argument to `poly` must indeed be polymorphic. For example, the following fails:
375−test = poly (\n -> n + 1)
378−since the skolemized type variable `a` does not unify with `Number`.
382−All types can be inferred, but annotations can optionally be provided.
386−There are two primitive kinds, the kind `*` of types and the kind `!` of effects.
388−For each kind `k` there is also a kind `# k` of rows, with types of kind `k`. For example `# *` is the kind of rows of types, as used to define records, and `# !` is the kind of rows of effects, used to define the monad `Eff` of extensible effects.
390−Higher kinded types are also supported. That is, a type variable can refer to not only a type or a row, but a type constructor, or row constructor etc.
394−Syntax is whitespace sensitive. The general rule of thumb is that declarations which span multiple lines should be indented past the column on which they were first defined on their subsequent lines.
396−That is, the following is valid:
412−Blocks are collections of statements wrapped in braces `{ ... }`. Blocks must return a value of the same type on every branch of execution.
414−The following types of statement are supported:
416−- Variable introduction
417−- Variable assignment
421−- If-Then-Else statements
423−Here is an example of a power function defined using a block:
428− for (i <- 0 until p) {
435−Blocks enable local mutation of their variables, but mutation is not allowed in general. The type system prevents mutable variables from escaping their scope.
437−That is, while the example above is valid, the following does not compile:
446−The variable `n` is not mutable, and so the assignment in the first line of the `do` block is not allowed.
448−This function can be rewritten as follows:
460−For loops look like this:
465− for (i <- 0 until 10) {
472−The bounds `0` and `10` are inclusive and exclusive respectively.
476−For each loops loop over the elements in an array using the `Object.forEach` method. A polyfill may be required for some browsers:
481− foreach (i in arr) {
490−The syntax of a while loop is similar to a foreach loop:
504−## If-Then-Else Statements
506−Else branches are optional, and may contain further `if` statements, just as in Javascript:
524−## If-Then-Else Expressions
526−The `if`, `then` and `else` keywords can also be used to create conditional expressions. In this case, the `else` block is always required.
531−conditional = if 2 > 1 then "ok" else "oops"
536−The `do` keyword introduces simple syntactic sugar for monadic expressions.
538−Here is an example, using the maybe monad:
541−data Maybe a = Nothing | Just a
543−instance Monad Maybe where
545− (>>=) Nothing _ = Nothing
546− (>>=) (Just a) f = f a
548−isEven n | n % 2 == 0 = Just {}
559−`isEven` adds two values of type `Maybe Number` and returns their sum, if the sum is even. If the sum is odd, `evenSum` returns `Nothing`.
561−This example illustrates the following aspects of `do` notation:
563−- The corresponding type constructor must be an instance of the `Prelude.Monad` type class, which defines the `ret` and `>>=` functions.
564−- Statements can have the following form:
565− - `a <- x` which desugars to `m.bind x (\a -> ...)`
566− - `let a = x` which desugars to `(\a -> ...)(x)`
567− - `x` which desugars to `m.bind x (\_ -> ...)` or just `x` if this is the last statement.
569−Not illustrated here, but equally valid is the use of a binder on the left hand side of `<-` or `=`. For example:
577−A pattern match failure will generate a runtime exception, just as in the case of a regular `case` statement.
581−Pattern matching deconstructs a value to bring zero or more expressions into scope. Pattern matches are introduced with the `case` keyword.
583−Pattern matches have the following general form
592−Pattern matching can also be used in the declaration of functions, as we have already seen:
595−fn pattern_1 ... pattern_n = result
598−Any of the above types of pattern are also valid when introducing functions. In addition, patterns can also be grouped in parentheses to introduce multiple-arugument functions. For example,
601−example x (y, z) w = x * y + z * w
604−The following pattern types are supported:
615−Patterns need not be exhaustive. A pattern match failed exception will be thrown at runtime if no pattern matches the input.
619−The wilcard `_` matches any input and brings nothing into scope:
628−Literal patterns are provided to match on primitives:
646−A variable pattern matches any input and binds that input to its name:
650− result -> bar(result)
655−Array patterns match an input which is an array, and bring its elements into scope.
660−f = \arr -> case arr of
662− [x, y] -> x * y + f xs
666−Here, the first pattern only matches arrays of length one, and brings the first element of the array into scope.
668−The second pattern matches arrays with two elements, and brings the first and second elements into scope.
672−The head and tail of a non-empty array can be matched by using a cons pattern:
675−add = \arr -> case arr of
677− x : xs -> x + add xs
680−`:` associates to the right:
683−addPairs = \arr -> case arr of
684− x : y : xs -> x * y + addPairs xs
690−Record patterns match an input which is a record, and bring its properties into scope.
694− { foo = "Foo" } -> o.bar
700−The patterns above can be combined to create larger patterns.
706− { arr = x : _, take = "car" } -> x
707− { arr = _ : x : _, take = "cadr" } -> x
713−Named patterns bring additional names into scope when using nested patterns. Any pattern can be named by using the `@` symbol:
716−f = \arr -> case arr of
717− a@(_ : _ : _) -> true
721−Here, in the first pattern, any array with two or more elements will be matched and bound to the variable `a`.
725−Guards are used to impose additional constraints inside a pattern using boolean-valued expressions, and are introduced with a pipe after the pattern:
728−evens = \arr -> case arr of
730− x : xs | x % 2 == 0 -> 1 + evens xs
734−When defining a function, guards appear after all patterns:
737−greater x y | x > y = true
743−For convenience, it is possible to declare a synonym for a type using the `type` keyword. Type synonyms can include type arguments.
748−type Foo = { foo :: Number, bar Number }
750−addFoo :: Foo -> Number
751−addFoo = \o -> o.foo + o.bar
755−Properties on records can be updated using the following syntax: `o { key = value, ..., key = value }`
757−For example, the following function increments the `foo` property on its argument:
760−incr = \o -> o { foo = o.foo + 1 }
763−The generated Javascript assumes the existence of a method called `Object.extend` such that `Object.extend(o, p)` takes an object `o` and generates a shallow copy of `o` including the properties of `p`. A simple JQuery implementation of this specification is
766−Object.prototype.extend = function(o, p) {
767− return $.extend({}, o, p);
773−In addition to the standard operators, user-defined infix operators can be created by enclosing names in parentheses:
775−E.g. to create a synonym for string concatenation:
778−(<>) = \s1 s2 -> s1 ++ s2
780−greeting = "Hello" <> "World!"
783−Regular functions can be used as operators by enclosing their names in backticks:
786−foo = \x y -> x * y + y
791−Fixity declarations can associate a precedence level, which is a natural number, to a user-defined operator, and specify which way it associates:
800−Modules are introduced using the `module` keyword. All code must be placed in a module.
802−Introduce a module as follows, with a list of declarations:
810−Names may be qualified by using a dot:
817−All the names in a module can be aliased using the `import` declaration:
823−You can also limit which names are going to be aliased:
829−## Foreign Function Interface
831−The `foreign import` keyword declares a value which is defined in Javascript, and its type:
834−foreign import pow :: (Number, Number) -> Number
837−To declare a new type with no constructors, use `foreign import data` and provide the kind:
840−foreign import data IO :: * -> *
842−foreign import console :: {
843− log :: String -> IO {}
847−To alias a name of a field defined on a Javascript type to a PureScript function, use `foreign import member`. For example, to define a function `length` which accesses the `length` member of an array:
850−foreign import member "length" length :: forall a. [a] -> Number
855−PureScript has basic support for type classes via the `class` and `instance` keywords.
857−Type class instances must be of the form `String`, `Number`, `Boolean`, `[t]` or `C t1 ... tn`, and only a single type class parameter is supported.
859−Type class instances are resolved based on the order in which they appeared in the source files. In particular, overlapping instances are permitted.
865−instance Show String where
868−instance Show Boolean where
870− show false = "false"
872−instance (Show a) => Show [a] where
873− show arr = "[" ++ showArray arr ++ "]"
875−showArray :: forall a. (Show a) => [a] -> String
877−showArray [x] = show x
878−showArray (x:xs) = show x ++ ", " ++ showArray xs
880−example = show [true, false]