Skip to content

Instantly share code, notes, and snippets.

Interfaces and Sum Types

The way different programming languages implement the mapping of runtime polymorphic values to code both at the source level and in the language implementation is a defining characteristic. There are two opposite approaches that languages facilitate to varying degrees:

  1. Interfaces / Traits / Abstract Classes / Inheritance / Method Overriding (from here on, just "Interfaces")
  2. Sum Types / Algebraic Data Types / Tagged Unions / Pattern Matching (from here on, just "Sum Types")

Example

You have two types: A, containing a string, and B, containing an int, and two operations: x and y.

@pdarragh
pdarragh / papers.md
Last active April 17, 2024 19:29
Approachable PL Papers for Undergrads

Approachable PL Papers for Undergrads

On September 28, 2021, I asked on Twitter:

PL Twitter:

you get to recommend one published PL paper for an undergrad to read with oversight by someone experienced. the paper should be interesting, approachable, and (mostly) self-contained.

what paper do you recommend?

// Example: Opcode dispatch in a bytecode VM. Assume the opcode case dispatching is mispredict heavy,
// and that pc, ins, next_ins, next_opcase are always in registers.
#define a ((ins >> 8) & 0xFF)
#define b ((ins >> 16) & 0xFF)
#define c ((ins >> 24) & 0xFF)
// Version 1: Synchronous instruction fetch and opcode dispatch. The big bottleneck is that given how light
// the essential work is for each opcode case (e.g. something like ADD is typical), you're dominated
// by the cost of the opcode dispatch branch mispredicts. When there's a mispredict, the pipeline restarts
defmodule End do
defmodule Region do
defstruct name: "", population: 0, south_edge: 0
end
defp tally(lines, regions) do
Enum.reduce(lines, regions, fn line, regions ->
fields = String.split(line, "\t")
{latitude, _} = Enum.at(fields, 4) |> Float.parse()
{population, _} = Enum.at(fields, 14) |> Integer.parse()
@ikskuh
ikskuh / async_await.zig
Last active July 11, 2022 08:41
Async Await in 60 LOC
const std = @import("std");
// usage:
fn asyncMain() !void {
// Start two interleaving tasks
var task_a = async waitUntilAndPrint(start + 1000, start + 1200, "task a");
var task_b = async waitUntilAndPrint(start + 500, start + 1300, "task b");
var task_c = async waitUntilAndPrint(start + 800, start + 1100, "task c");
await task_a;
@kprotty
kprotty / fib.zig
Last active March 20, 2024 16:12
small event loop
const std = @import("std");
const allocator = std.heap.page_allocator;
pub fn main() !void {
const n = 10;
const ret = try (try Task.run(fib, .{n}));
std.debug.warn("fib({}) = {}\n", .{n, ret});
}
fn fib(n: usize) std.mem.Allocator.Error!usize {
@CarlosDomingues
CarlosDomingues / python-poetry-cheatsheet.md
Last active June 19, 2024 21:50
Python Poetry Cheatsheet

Create a new project

poetry new <project-name>

Add a new lib

poetry add <library>

Remove a lib