Parent post: Thoughts on building a PureScript app
Calling PureScript functions
Lets create a simple module which will contain an
1 2 3 4
Saving this little script to
MyMath.purs and compiling it with:
psc MyMath.purs --browser-namespace PureScript > index.js
will generate a file which we can import in our test
1 2 3 4 5 6 7 8
Upon loading the script, we can access our function like this:
A couple of notes here:
--browser-namespace PureScriptflag I used told the compiler to export all modules in an object called
PureScript. If you leave this flag out, the name of this object will default to
- The reason why I call
MyMath.add(3)(4)in this rather strange way is because functions exported by PureScript always take exactly zero or one arguments.
MyMath.add(3)in fact returns a new function which takes the second argument, which feels really strange if you’ve never seen it before. If you want to know more about why it is like that, you can check the Wiki article on currying
Co calling PureScript code is easy:
- Write your modules
- Compile them into an
- Import the script in the
- Call your functions
The first resource you want to check out is the PureScript documentation on Foreign Function Interfaces.
Let’s upgrade the example above. We’ll define a function in the global scope:
1 2 3 4 5 6 7 8 9 10 11
Now let’s reference it from our compiled PureScript code:
1 2 3 4 5 6 7 8 9
And finally, let’s call our new function:
- Have the function defined in the scope
- Import it with
foreign import yourFunction :: InputType -> OutputType
- Use it like it’s a PureScript function
Hopefully, life makes sense now.
Important closing notes
There are other ways of compiling PureScript
Instead of running
psc which combines all modules in a single file, you can use
psc-make. The difference is:
psc-make exports CommonJS modules in separate folders in a directory called
This is particularly interesting if you’re using PureScript functions from Node.js. If you copy the contents of
output you should be able to do this:
You can define JS functions inline
Instead of writing:
which relies on having
happySadParity in scope, you can just define the function on the fly:
1 2 3 4
Is it safe?
No, it’s not. By binding code this way, you get none of the safety that PureScript offers.
Think about it. If you shove an exception in a PureScript function that doesn’t know how to handle it, well, your script will crash, no matter how typechecked the language is.
undefined — you’re screwed.
How do I make it safe?
I’ll cover that topic in another post which I’ll link here.