Skip to content

Instantly share code, notes, and snippets.

@eduardoleon
Created December 17, 2014 11:02
Show Gist options
  • Save eduardoleon/54591a75434d41d42b6a to your computer and use it in GitHub Desktop.
Save eduardoleon/54591a75434d41d42b6a to your computer and use it in GitHub Desktop.
Pattern matching vs. Visitor pattern
import Control.Applicative
data Person = Boy String
| Girl String
data Animal = Dog String
| Cat String
| Bug
boy (Dog n) = " plays with " ++ n
boy (Cat n) = " chases " ++ n ++ " away"
boy Bug = " almost crushes a bug"
girl (Dog n) = " pets " ++ n
girl (Cat n) = " pets " ++ n
girl Bug = " runs away from a bug"
test (Boy n) = (n ++) . boy
test (Girl n) = (n ++) . girl
main = mapM_ putStrLn
$ test <$> [Boy "Peter", Girl "Cindy"]
<*> [Dog "Rocky", Cat "Fluffy", Bug]
interface Animal {
void accept(Person person);
}
final class Dog implements Animal {
String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void accept(Person person) {
person.visitDog(this);
}
}
final class Cat implements Animal {
String name;
public Cat(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void accept(Person person) {
person.visitCat(this);
}
}
final class Bug implements Animal {
public Bug() {}
public void accept(Person person) {
person.visitBug(this);
}
}
// Persons visit Animals
interface Person {
void visitDog(Dog dog);
void visitCat(Cat cat);
void visitBug(Bug bug);
}
final class Boy implements Person {
String name;
public Boy(String name) {
this.name = name;
}
public void visitDog(Dog dog) {
System.out.print(this.name);
System.out.print(" plays with ");
System.out.println(dog.getName());
}
public void visitCat(Cat cat) {
System.out.print(this.name);
System.out.print(" chases ");
System.out.print(cat.getName());
System.out.println(" away ");
}
public void visitBug(Bug bog) {
System.out.print(this.name);
System.out.println(" almost crushes a bug");
}
}
final class Girl implements Person {
String name;
public Girl(String name) {
this.name = name;
}
public void visitDog(Dog dog) {
System.out.print(this.name);
System.out.print(" pets ");
System.out.println(dog.getName());
}
public void visitCat(Cat cat) {
System.out.print(this.name);
System.out.print(" pets ");
System.out.println(cat.getName());
}
public void visitBug(Bug bog) {
System.out.print(this.name);
System.out.println(" runs away from a bug");
}
}
public final class Main {
public static void main(String[] args) {
Person[] persons = new Person[] {
new Boy ("Peter"),
new Girl("Cindy")
};
Animal[] animals = new Animal[] {
new Dog("Rocky"),
new Cat("Fluffy"),
new Bug()
};
for (Person person : persons)
for (Animal animal : animals)
animal.accept(person);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment