on 6d45ede help sign in
86 lines 2.8 kB history raw
1---
2navhome: /docs
3title: Scala
4sort: 4
5next: true
6---
8# Scala
10From [Steve Randy Waldman](https://github.com/swaldman/nnnock/blob/master/src/main/scala/com/mchange/sc/v1/nnnock/package.scala):
12```
13package object nnnock {
15 sealed trait Noun;
16 case class Atom( value : Int ) extends Noun;
17 case class Cell( head : Noun, tail : Noun ) extends Noun;
18 implicit def toAtom( value : Int ) : Atom = Atom( value );
19 implicit def toInt( atom : Atom ) : Int = atom.value;
21 def nock( a : Noun ) : Noun = *(a)
23 object Cell {
24 private def apply( nl : List[Noun] ) : Cell = {
25 nl match {
26 case a :: b :: Nil => Cell(a, b);
27 case a :: b :: c :: Nil => Cell(a, Cell(b, c));
28 case a :: b :: c :: tail => Cell(a, this.apply( b :: c :: tail ) );
29 }
30 }
31 def apply(a : Noun, b : Noun, tail : Noun*) : Cell = apply( a :: b :: tail.toList );
32 }
34 def ?( noun : Noun ) : Noun = noun match {
35 case _ : Cell => 0;
36 case _ : Atom => 1;
37 }
39 @tailrec def plus( noun : Noun ) : Noun = noun match {
40 case a : Atom => 1 + a;
41 case c : Cell => plus( c ); //intentional endless spin
42 }
44 def heq( noun : Noun ) : Atom = noun match {
45 case Cell( a : Atom, b : Atom ) => if ( a == b ) 0 else 1;
46 case Cell( a : Cell, b : Atom ) => 1;
47 case Cell( a : Atom, b : Cell ) => 1;
48 case Cell( a : Cell, b : Cell ) => if ((heq( Cell( a.head, b.head ) ) | heq( Cell( a.tail, b.tail ) )) == 0) 0 else 1;
49 case a : Atom => heq( a ); //intentional endless spin
50 }
52 def /( noun : Noun ) : Noun = noun match {
53 case Cell(Atom(1), a) => a;
54 case Cell(Atom(2), Cell(a, b)) => a;
55 case Cell(Atom(3), Cell(a, b)) => b;
56 case Cell(Atom(value), b ) => {
57 val a = value / 2;
58 val num = if ( value % a == 0 ) 2 else 3;
59 /(Cell(num, /(Cell(a, b))));
60 }
61 case a => /( a ); //intentional endless spin
62 }
64 def *( noun : Noun ) : Noun = noun match {
65 case Cell( a, Cell(Cell(b, c), d) ) => Cell( *(Cell(a,b,c)), *(Cell(a,d)) );
66 case Cell( a, Cell(Atom(value), tail) ) => {
67 (value, tail) match {
68 case (0, b) => /( Cell(b, a) );
69 case (1, b) => b;
70 case (2, Cell(b, c)) => *( Cell( *( Cell(a,b) ), *( Cell(a,c) ) ) );
71 case (3, b) => ?( *( Cell(a,b) ) );
72 case (4, b) => plus( *( Cell(a,b) ) );
73 case (5, b) => heq( *( Cell(a,b) ) );
74 case (6, Cell(b, Cell(c, d))) => *( Cell(a,2,Cell(0,1),2,Cell(1,c,d),Cell(1,0),2,Cell(1,2,3),Cell(1,0),4,4,b) ); //wtf?
75 case (7, Cell(b, c)) => *( Cell(a,2,b,1,c) );
76 case (8, Cell(b, c)) => *( Cell(a,7,Cell(Cell(7,Cell(0,1),b),0,1),c) ); //wtf2
77 case (9, Cell(b, c)) => *( Cell(a,7,c,2,Cell(0,1),0,b) );
78 case (10, Cell(Cell(b,c),d)) => *( Cell(a,8,c,7,Cell(0,3),d) );
79 case (10, Cell(b, c)) => *( Cell(a,c) );
80 case _ => *( noun ); //intentional endless spin
81 }
82 }
83 case a => *( a ); //intentional endless spin
84 }
86```