Skip to content

Instantly share code, notes, and snippets.

View kevinpet's full-sized avatar

Kevin Peterson kevinpet

View GitHub Profile
@kevinpet
kevinpet / PartitionFoos.java
Last active August 29, 2015 14:15
Java void visitor
class PartitionFoos {
void doStuff(Collection<Foo> foos) {
final List<Bar> bars = new ArrayList<>();
final List<Baz> bazes = new ArrayList<>();
for (Foo f : foos) {
f.match(new Visitor<Void>() {
@Override
public Void caseBar(Bar b) {
bars.add(b);
@kevinpet
kevinpet / DefaultFooVisitor.java
Created February 8, 2015 21:52
Java default visitor
class DefaultFooVisitor<T> implements Foo.Visitor<T> {
T defaultValue;
private DefaultFooVisitor(T defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public T caseBar(Bar b) {
return defaultValue;
abstract class Foo {
abstract <T> T match(Visitor<T> visitor);
interface Visitor<T> {
T caseBar(Bar b);
T caseBaz(Baz b);
}
static class Bar extends Foo {
final int bar;
@kevinpet
kevinpet / OoFoo.java
Created February 8, 2015 21:33
OO Java
abstract class OoFoo {
abstract void handle();
static class Bar extends OoFoo {
private int bar;
private Bar(int bar) {
this.bar = bar;
}
@kevinpet
kevinpet / BadFoo.java
Created February 8, 2015 21:24
Java instanceof
abstract class BadFoo {
static class Bar extends BadFoo {
int bar;
private Bar(int bar) {
this.bar = bar;
}
}
@kevinpet
kevinpet / Foo.java
Created February 8, 2015 20:39
Java destructuring visitor example
abstract class Foo {
abstract <T> T match(Visitor<T> visitor);
interface Visitor<T> {
T caseManyBar();
T caseBar(int i);
T caseBaz(String s);
}
static class Bar extends Foo {
@kevinpet
kevinpet / patterns.swift
Created September 12, 2014 22:45
Enum pattern matching in swift
enum Foo {
case Bar(bar: Int)
case Baz(baz: String)
}
func handle(f: Foo) -> Any {
switch f {
case .Bar(let bar):
return bar
case .Baz(let baz):
@kevinpet
kevinpet / patterns.sc
Last active August 29, 2015 14:04
Scala case class field extraction
object patterns {
abstract class Foo
case class Bar(val bar: Int) extends Foo
case class Baz(val baz: String) extends Foo
def handle(f: Foo) =
f match {
case Bar(i) if (i > 10) => 10
case Bar(i) => i
case Baz(s) => s
@kevinpet
kevinpet / patterns.sc
Last active August 29, 2015 14:04
Scala Pattern Matching
object patterns {
abstract class Foo
class Bar(val bar: Int) extends Foo
class Baz(val baz: String) extends Foo
def handle(f: Foo) =
f match {
case b: Bar => b.bar
case b: Baz => b.baz
}
class Account {
private Strategy strategy;
private Map<String, Double> investments;
boolean addInvestment(String symbol, double fraction, double riskiness) {
if (strategy.isRiskAcceptable(fraction, riskiness)) {
investments.put(symbol, fraction);
return true;
}
return false;