File tree Expand file tree Collapse file tree 3 files changed +77
-0
lines changed Expand file tree Collapse file tree 3 files changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ enum HLst {
2+ case HCons [+ Hd , + Tl <: HLst ](hd : Hd , tl : Tl )
3+ case HNil
4+ }
5+
6+ object Test {
7+ import HLst ._
8+ def length (hl : HLst ): Int = hl match {
9+ case HCons (_, tl) => 1 + length(tl)
10+ case HNil => 0
11+ }
12+ def sumInts (hl : HLst ): Int = hl match {
13+ case HCons (x : Int , tl) => x + sumInts(tl)
14+ case HCons (_, tl) => sumInts(tl)
15+ case HNil => 0
16+ }
17+ def main (args : Array [String ]) = {
18+ val hl = HCons (1 , HCons (" A" , HNil ))
19+ assert(length(hl) == 2 , length(hl))
20+ assert(sumInts(hl) == 1 )
21+ }
22+ }
Original file line number Diff line number Diff line change 1+ enum Tree [T ] {
2+ case True extends Tree [Boolean ]
3+ case False extends Tree [Boolean ]
4+ case Zero extends Tree [Int ]
5+ case Succ (n : Tree [Int ]) extends Tree [Int ]
6+ case Pred (n : Tree [Int ]) extends Tree [Int ]
7+ case IsZero (n : Tree [Int ]) extends Tree [Boolean ]
8+ case If (cond : Tree [Boolean ], thenp : Tree [T ], elsep : Tree [T ])
9+ }
10+
11+ object Test {
12+ import Tree ._
13+
14+ def eval [T ](e : Tree [T ]): T = e match {
15+ case True => true
16+ case False => false
17+ case Zero => 0
18+ case Succ (f) => eval(f) + 1
19+ case Pred (f) => eval(f) - 1
20+ case IsZero (f) => eval(f) == 0
21+ case If (cond, thenp, elsep) => if (eval(cond)) eval(thenp) else eval(elsep)
22+ }
23+
24+ val data = If (IsZero (Pred (Succ (Zero ))), Succ (Succ (Zero )), Pred (Pred (Zero )))
25+
26+ def main (args : Array [String ]) = {
27+ println(s " $data --> ${eval(data)}" )
28+ }
29+ }
Original file line number Diff line number Diff line change 1+ enum class Planet (mass : Double , radius : Double ) {
2+ private final val G = 6.67300E-11
3+ def surfaceGravity = G * mass / (radius * radius)
4+ def surfaceWeight (otherMass : Double ) = otherMass * surfaceGravity
5+ }
6+ object Planet {
7+ case MERCURY extends Planet (3.303e+23 , 2.4397e6 )
8+ case VENUS extends Planet (4.869e+24 , 6.0518e6 )
9+ case EARTH extends Planet (5.976e+24 , 6.37814e6 )
10+ case MARS extends Planet (6.421e+23 , 3.3972e6 )
11+ case JUPITER extends Planet (1.9e+27 , 7.1492e7 )
12+ case SATURN extends Planet (5.688e+26 , 6.0268e7 )
13+ case URANUS extends Planet (8.686e+25 , 2.5559e7 )
14+ case NEPTUNE extends Planet (1.024e+26 , 2.4746e7 )
15+ }
16+ object Test {
17+ def main (args : Array [String ]) = {
18+ import Planet ._
19+ assert(enumValueNamed(" SATURN" ) == SATURN )
20+ assert(enumValue(2 ) == EARTH )
21+ val earthWeight = 100
22+ val mass = earthWeight/ EARTH .surfaceGravity
23+ for (p <- enumValues)
24+ println(s " Your weight on $p is ${p.surfaceWeight(mass)}" )
25+ }
26+ }
You can’t perform that action at this time.
0 commit comments