Skip to content

Commit c07216a

Browse files
committed
Merge pull request #6 from Mironor/master
Added solutions for chapter 1, exercise 1 to 5 and chapter 2 exercise 1 to 3
2 parents 691d05d + 3f40bf4 commit c07216a

File tree

3 files changed

+67
-5
lines changed

3 files changed

+67
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package org.learningconcurrency.exercises
2+
3+
object CH1Solutions extends App{
4+
5+
def compose[A, B, C](g: B => C, f: A => B): A => C = g compose f
6+
// Alternative solutioin: = x => g(f(x))
7+
8+
def fuse[A, B](a: Option[A], b: Option[B]): Option[(A, B)] = for {
9+
aVal <- a
10+
bVal <- b
11+
} yield (aVal, bVal)
12+
13+
def check2[T](xs: Seq[T])(pred: T => Boolean): Boolean = xs.forall {x =>
14+
try {
15+
pred(x)
16+
} catch {
17+
case _: Exception => false
18+
}
19+
)
20+
21+
def permutations(x: String): Seq[String] = x.permutations.toList
22+
23+
}
24+
25+
case class Pair[P, Q](first: P, second: Q)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package org.learningconcurrency.exercises
2+
3+
import org.learningconcurrency.ch2.thread
4+
5+
6+
object CH2Solutions extends App{
7+
8+
def parallel[A, B](a: =>A, b: =>B): (A, B) = {
9+
var aVal: A = null.asInstanceOf[A]
10+
var bVal: B = null.asInstanceOf[B]
11+
12+
val t1 = thread {
13+
aVal = a
14+
log(aVal.toString())
15+
}
16+
17+
val t2 = thread {
18+
bVal = b
19+
log(bVal.toString())
20+
}
21+
22+
t1.join()
23+
t2.join()
24+
25+
(aVal, bVal)
26+
}
27+
28+
def periodically(duration: Long)(f: () => Unit): Unit = {
29+
val worker = new Thread {
30+
while(true){
31+
f()
32+
Thread.sleep(duration)
33+
}
34+
}
35+
36+
worker.setName("Worker")
37+
worker.setDaemon(true)
38+
worker.start()
39+
}
40+
}
41+
42+
}
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
package org.learningconcurrency
22

33

4-
5-
6-
7-
84
package object exercises {
9-
105
}

0 commit comments

Comments
 (0)