Notes

PureScript

PureScript is my prefered language for Type Driven Developement in frontend.

1 Must read

2 Cheatsheet

2.1 Literal

2.2 Number

2.2.1 JS

let a = 1
let b = 1.2

2.2.2 PureScript

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

2.3 String

2.3.1 JS

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

2.3.2 PureScript

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

2.4 Boolean

2.4.1 JS

let a = true
let b = false

2.4.2 PureScript

a :: Boolean
a = true

b :: Boolean
b = false

2.5 Records

2.5.1 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})
}

2.5.2 PureScript

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

b = a {key1 = "new value1"}

updateKey2To = _ {key2 = _}

2.6 Function

2.6.1 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)
}

2.6.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)

2.7 Control Flow

2.8 If-Else

2.8.1 JS

let tof = true ? true : false

2.8.2 PureScript

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

2.9 Scope

2.9.1 JS

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

2.9.2 PureScript

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

2.10 Pattern Matching

2.10.1 JS ES proposal

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

2.10.2 PureScript

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

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

2.11 Do Notaion / FlatMap

2.11.1 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))

2.11.2 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

2.12 Modules

2.13 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

2.14 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'

3 Reference