functor in go
Apr. 29th, 2022 08:13 amScala: Free, back with a vengeance
Jun. 3rd, 2021 08:57 amhttps://www.youtube.com/watch?v=2yRtxYbV1h4
More SICP wisdoms
Jan. 29th, 2020 10:58 pm70 Observe that, for any two streams, there is in general more than one acceptable order of interleaving. Thus, technically, ‘merge’ is a relation rather than a function—the answer is not a deterministic function of the inputs. We already mentioned (footnote 38 ) that nondeterminism is essential when dealing with concurrency. The merge relation illustrates the same essential nondeterminism, from the functional perspective.
71 The object model approximates the world by dividing it into separate pieces. The functional model does not modularize along object boundaries. The object model is useful when the unshared state of the ‘objects’ is much larger than the state that they share. An example of a place where the object viewpoint fails is quantum mechanics, where thinking of things as individual particles leads to paradoxes and confusions. Unifying the object view with the functional view may have little to do with programming, but rather with fundamental epistemological issues.
package scalakittens.experiments
object CopyDL extends App {
/*
The problem is this: we have a linked list of nodes; each node has a value and a pointer to another node anywhere in the list.
We have to make a copy of this list.
Impossible without mutability or laziness. Haskell solution is laziness. Here's my solution.
*/
trait Node {
def value: Int
def next: Node
def random: Node
}
class DataNode(
val value: Int,
var next: Node,
var random: Node) extends Node
def inverseIndex(index: Array[Node]): Map[Node, Int] = {
index.indices map { i => index(i) -> i } toMap
}
def randIndex(index: Array[Node], inverseIndex: Map[Node, Int]): Array[Int] = {
index map (_.random) map inverseIndex
}
def copy(nodes: Iterable[Node]): Iterable[Node] = {
val index = nodes.toArray
val ii = inverseIndex(index).withDefaultValue(-1)
lazy val newNodes: List[IndirectNode] = index.indices map {
i =>
val old = index(i)
IndirectNode(old.value, ii(old.next), ii(old.random))
} toList
case class IndirectNode(value: Int, nextId: Int, rndId: Int) extends Node {
override def next = if (nextId < 0) null else newNodes(nextId)
override def random = if (rndId < 0) null else newNodes(rndId)
def valueOf(node: Node) = Option(node) map (_.value.toString) orNull
override def toString: String =
s"Node($value, ->${valueOf(next)}, ->${valueOf(random)})"
}
newNodes
}
val n1 = new DataNode(101, null, null)
val n2 = new DataNode(102, null, n1)
val n3 = new DataNode(103, n1, n2)
//n2.next = n3
n1.next = n2
n1.random = n3
val copied = copy(n1::n2::n3::Nil)
println(copied)
}