1
file:purescript/cheatsheet.org
source link: https://blog.oyanglul.us/purescript/cheatsheet.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
PureScript Cheat Sheet For JavaScript Developers
PureScript Cheat Sheet For JavaScript Developers
Table of Contents
Literal
Number
let a = 1
let b = 1.2
PureScript
a :: Int
a = 1
b :: Number
b = 1.2
String
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
let a = true
let b = false
PureScript
a :: Boolean
a = true
b :: Boolean
b = false
Records
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
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
let tof = true ? true : false
PureScript
tof :: Boolean
tof = if true then true else false
Scope
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
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
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'
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK