Skip to content

Instantly share code, notes, and snippets.

View wongjiahau's full-sized avatar

WJH wongjiahau

  • Malaysia
View GitHub Profile
@wongjiahau
wongjiahau / .js
Last active December 23, 2019 15:11
Jia Hau's syntax idea
// This language is based on the idea of json-like objects
// This is a comment
// Tagged union
// Like OCaml, the tag is not associated with the type name, in this case `nat`
// Essentially, `nat` is just a alias for the tagged union
type Nat = {#zero} | {#succ, of: nat}
// Variable & object initialization
people = {name='John', hobby='type theory'}
const getArea = (shape: Shape) => {
switch(shape.label) {
case 'circle': return Math.PI * Math.pow(shape.radius, 2)
case 'triangle': return 0.5 * shape.base * shape.height
case 'rectangle': return shape.height * shape.width
}
}
const newShape2: Shape = {
label: 'circle',
width: 30 // You'll get a compiler error saying `width` does not exists when label is `circle`
}
type Shape = {
kind: 'circle'
radius: number
} | {
kind: 'rectangle'
width: number
height: number
} | {
kind: 'triangle'
base: number
interface Shape {}
class Circle extends Shape {
constructor(public radius: number) {}
}
class Rectangle extends Shape {
construtor(public height: number, public width: number) {}
}
class Triangle extends Shape {
constructor(public height: number, public base: number) {}
}
interface ShapeV2 {
label: 'rectangle' | 'circle' | 'triangle'
radius ?: number // only for circle
height ?: number // only for triangle and rectangle
width ?: number // only for rectangle
base ?: number // only for triangle
}
const newShape1: Shape = { width: 30, base: 40 } // invalid combination of properties
const newShape2: Shape = { height: 40 } // missing base or width
const getArea = (shape: Shape) => {
if (shape.radius) {
return Math.PI * Math.pow(shape.radius, 2)
}
else if (shape.height && shape.width) {
return shape.height * shape.width
}
else if (shape.base && shape.height) {
return 0.5 * shape.base * shape.height
}
@wongjiahau
wongjiahau / Shape1.ts
Last active July 2, 2019 14:48
Typescript Discriminated Union Example 1
interface Shape {
radius ?: number
height ?: number
width ?: number
base ?: number
}
@wongjiahau
wongjiahau / hm.tex
Last active May 29, 2022 03:46
The latex code for Hindley Milner Type System.
\documentclass{article}
\begin{document}
\begin{table}[h!]
\begin{center}
\begin{tabular}{cl}
\\
\(\frac
{x \ : \ \sigma \ \in \ \Gamma}