HOME | EDIT | RSS | ABOUT | GITHUB

PureScript Cheat Sheet For JavaScript Developers

Literal

Number

JS

let a = 1
let b = 1.2

PureScript

a :: Int
a = 1
b :: Number
b = 1.2

String

JS

let a = "yay"
let multiline = `first line
second line
third line`
let concatString = "a" + "b"

PureScript

a :: String
a = "yay"
multiline = """first line
second line
third line"""
concatString = "a" <> "b"

Boolean

JS

let a = true
let b = false

PureScript

a :: Boolean
a = true

b :: Boolean
b = false

Records

JS

let a = {key1: "value1", key2: true}

let b = Object.assign({}, a, {key1: "new value1"})

function updateKey2To(record) {
  return (value) => Object.assign({}, record, {key2: value})
}

PureScript

a :: {key1:: String, key2:: Boolean}
a = {key1: "value1", key2: true}

b = a {key1 = "new value1"}

updateKey2To = _ {key2 = _}

Function

JS

function sum(x, y) { return x + y }
let lambdaSum = (x, y) => (x + y)

function fib(n) {
  if(n == 0) return 1
  else if(n == 1) return 1
  else return fib(n-1) + fib(n-2)
}

PureScript

sum :: Int -> Int -> Int
sum x y = x + y

lambdaSum :: Int -> Int -> Int
lambdaSum = \x y -> x + y

fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

Control Flow

If-Else

JS

let tof = true ? true : false

PureScript

tof :: Boolean
tof = if true then true else false

Scope

JS

let a = 1
function inScope() {
  let a = 2
  return a
}

PureScript

a = 1
inScope = a
  where a = 2
-- or
inScope = let a = 2
  in a

Pattern Matching

JS ES proposal

let res = {status: 404}
let entity = case (res) {
  when {status: 200, body: b} ->
    b
  when {status: s} ->
    throw "error" + s
}

PureScript

res :: {status:: Int, body:: String}
res = {status: 404, body: ""}

entity = case res of
  {status: 200, body: b} -> Right b
  e -> Left $ show e

Do Notaion / FlatMap

JS

JavaScript(ES2019) has flatMap for Array

let a = [1,2,3]
let b = [2,3,4]
let c = a.flatMap(x=> b.flatMap(y => x+y))

PureScript

flatMap in PureScript is the same as Haskell >>=

a = [1,2,3]
b = [2,3,4]
c = a >>= \x -> (b >>= \y -> x + y)

and you can use do notation for nicer syntax

a = [1,2,3]
b = [2,3,4]
c = do
  x <- a
  y <- b
  pure x + y

not only Array, you can flatMap on any kind that has Monad instance i.e. Maybe

Modules

JS

JavaScript modules are based on file directory

// import module from somefile.js
import {method} from './some-file'
// export module
const a = 1
export a

PureScript

While PureScript is namespace based

-- file ramdom-file-name.purs
module A where
a = 1

so just module name matter, the file name doesnot matter

module B where
import A
-- not import './ramdom-file-name'

Reference