Skip to content

Instantly share code, notes, and snippets.

View fogfish's full-sized avatar

fogfish

View GitHub Profile
/*
UnApply2 is like contra-map function for data type T that unwrap product type
*/
type UnApply2[T, A, B any] func(T) (A, B)
/*
ProductEq2 is a container, product of type trait instances.
Here, the implementation is a shortcut due to the absence of heterogeneous lists in Golang.
// ExampleType product type is product of primitive types int × string
type ExampleType struct {
A int
B string
}
// Instances of Eq type trait for primitive types
var (
Int Eq[int] = FromEq[int](equal[int])
String Eq[string] = FromEq[string](equal[string])
/*
FromEq is a combinator that lifts T ⟼ T ⟼ bool function to
an instance of Eq type trait
*/
type FromEq[T any] func(T, T) bool
// implementation of Eq type class
func (f FromEq[T]) Equal(a, b T) bool { return f(a, b)}
package ord
/*
Ord : T ⟼ T ⟼ Ordering
Each type implements compare rules, mapping pair of value to enum{ LT, EQ, GT }
*/
type Ord [T any] interface {
Eq[T]
type Haystack[T any] struct{ Eq[T] }
func (h Haystack[T]) Lookup(a T, b []T) bool {
for _, x := range b {
if h.Eq.Equal(a, x) {
return true
}
}
return false
}
package eq
/*
eqInt declares a new instance of Eq trait, which is a real type.
The real type "knows" everything about equality in its own domain.
The instance of Eq is created as type over string, it is an intentional
technique to create a namespace using Golang constants.
The instance of trait is referenced as eq.Int in the code.
*/
/*
Eq : T ⟼ T ⟼ bool
Each trait implements mapping pair of value to bool category using own
equality rules
*/
type Eq [T any] interface {
Equal(T, T) bool
}
@fogfish
fogfish / bomb.ts
Created March 9, 2021 17:40
AWS CDK Bomb 💣
import * as cdk from '@aws-cdk/core'
class MyResource extends cdk.Construct {
constructor(scope: cdk.Construct, id: string, l: number) {
super(scope, id)
for (const x of Array(10).keys()) {
(l === 0)
? new cdk.CfnJson(this, `${id}${x}`, {value: '0123456789abcdef'})
: new MyResource(this, `${id}${x}`, l - 1)
}
/*
go test -bench=. -test.benchmem=true -test.benchtime=10s
goos: darwin
goarch: amd64
BenchmarkDirectCall-12 1000000000 1.31 ns/op 0 B/op 0 allocs/op
BenchmarkInterface-12 1000000000 1.69 ns/op 0 B/op 0 allocs/op
BenchmarkHoF-12 1000000000 1.61 ns/op 0 B/op 0 allocs/op
class Text {
static f(str: TemplateStringsArray, ...args: Array<any>) {
return <A>(...props: Array<A>): string => {
const parsed = args.map((x, index) => (typeof x === 'function' ? x(props[index]) : x))
if (parsed.some(x => x === undefined)) {
return ''
}
return str.reduce((acc, substr, index) => acc + this.text(parsed[index - 1]) + substr)
}