Swapping two mutable values - queue

This is given as the structure of the queue
type 'a dqnode = {
v: 'a;
mutable next: 'a dqnode option;
mutable prev: 'a dqnode option;
}
type 'a deque = {
mutable head: 'a dqnode option;
mutable tail: 'a dqnode option;
}
I'm trying to reverse a queue and I know that I want to switch the pointers for each node. For example, if I match 'a dqnode option from the queue to Some n, then I want to change n.next <- n.prev and n.prev (in the original state) <- n.next
Is there a way of storing 'a dqnode option at the beginning of my code so that I can switch the two pointers?
Something like:
let newnode1:'a dqnode option = n.prev in
n.prev <- n.next; n.next <- newnode1
Otherwise, I just end up with two pointers in the n.next position.

Your description of the problem is entirely correct, and your proposed solution is also correct.

Related

For-comprehension for two arrays of the same length

I have two Seq[Array[Byte]] arrays:
var o1: Seq[Array[Byte]]
var o2: Seq[Array[Byte]]
//...
I need to mutate the o1 Seq of Arrays so that each array of o1 is replaced with Array of o2 of the same position iff the array of o2 has non-zero length.
Is it possible to do with for-comprehension?
This seems like a better job for zip
o1 zip o2 map { case (l, r) => if(r.nonEmpty) r else l }
If you don't like creating the intermediate seq with o1 zip o2, you could lazily build up the combination using iterators:
(o1.iterator zip o2.iterator map { case (l, r) => if(r.nonEmpty) r else l }).toList
If you really want to mutate, first make sure to use a collection.mutable.IndexedSeq since its mutation method (update) takes an index. If you try to mutate a general Seq, you might get O(n) updates due to linked list-ish structures.
for {
(replacement, index) <- o2.iterator.zipWithIndex
if replacement.nonEmpty
} o1(index) = replacement
This is actually just syntax sugar for something like:
o2.iterator.zipWithIndex.foreach {
case (replacement, index) =>
if(replacement.nonEmpty) o1.update(index, replacement)
}

Queue In Scala using list in scala

We can implement a queue in java simply by using ArrayList but in case of Scala Lists are immutable so how can I implement a queue using List in Scala.Somebody give me some hint about it.
This is from Scala's immutable Queue:
Queue is implemented as a pair of Lists, one containing the in elements and the other the out elements. Elements are added to the in list and removed from the out list. When the out list runs dry, the queue is pivoted by replacing the out list by in.reverse, and in by Nil.
So:
object Queue {
def empty[A]: Queue[A] = new Queue(Nil, Nil)
}
class Queue[A] private (in: List[A], out: List[A]) {
def isEmpty: Boolean = in.isEmpty && out.isEmpty
def push(elem: A): Queue[A] = new Queue(elem :: in, out)
def pop(): (A, Queue[A]) =
out match {
case head :: tail => (head, new Queue(in, tail))
case Nil =>
val head :: tail = in.reverse // throws exception if empty
(head, new Queue(Nil, tail))
}
}
var q = Queue.empty[Int]
(1 to 10).foreach(i => q = q.push(i))
while (!q.isEmpty) { val (i, r) = q.pop(); println(i); q = r }
With immutable Lists, you have to return a new List after any modifying operation. Once you've grasped that, it's straightforward. A minimal (but inefficient) implementation where the Queue is also immutable might be:
class Queue[T](content:List[T]) {
def pop() = new Queue(content.init)
def push(element:T) = new Queue(element::content)
def peek() = content.last
override def toString() = "Queue of:" + content.toString
}
val q= new Queue(List(1)) //> q : lists.queue.Queue[Int] = Queue of:List(1)
val r = q.push(2) //> r : lists.queue.Queue[Int] = Queue of:List(2, 1)
val s = r.peek() //> s : Int = 1
val t = r.pop() //> t : lists.queue.Queue[Int] = Queue of:List(2)
If we talk about mutable Lists, they wouldn't be an efficient structure for implementing a Queue for the following reason: Adding elements to the beginning of a list works very well (takes constant time), but popping elements off the end is not efficient at all (takes longer the more elements there are in the list).
You do, however, have Arrays in Scala. Accessing any element in an array takes constant time. Unfortunately arrays are not dynamically sized, so they wouldn't make good queues. They cannot grow as your queue grows. However ArrayBuffers do grow as your array grows. So that would be a great place to start.
Also, note that Scala already has a Queue class: scala.collection.mutable.Queue.
The only way to implement a Queue with an immutable List would be to use a var. Good luck!

Functional way to loop over nested list

I was given a question to compare two trees. Something like below:
case class Node(elem:String, child:List[Node])
In order to compare each elements of the trees, I have following functions:
def compare(n1:Node, n2:Node): Boolean {
if(n1.elem == n2.elem){
return compare(n1.child, n2.child)
}
}
def compare(c1:List[Node], c2:List[Node]): Boolean {
while (c1.notEmpty) {
//filter, map etc call function above to compare the element recursively
}
}
Basically algorithm is for each elements in n1, we are checking for a match in n2. I was told that this is very imperative way and not functional way. What would be a functional way to achieve this behaviour. In other words, how do we remove while loop when comparing the list of children?
Consider zipping both lists and using forall which holds true only if each and every predicate it processes evaluates to true; for instance like this,
def compare(c1: List[Node], c2: List[Node]): Boolean =
(c1.sorted zip c2.sorted).forall(c => compare(c._1,c._2))
Note that forall will halt the evaluations as it encounters the first false. Cases of unequal length lists of nodes may be tackled with zipAll by defining an EmptyNode class for padding length differences; also both lists empty may compare to true.
Update
Sorted lists of nodes for soundness following comment by #JohnB.
If I understood your question correctly, you want to compare every element of the first list with every element of the second list. The following code achieves this. It gets rid of the while loop via a tail-recursion.
import scala.annotation.tailrec
def cmp(a:Int, b:Int) = a > b
#tailrec
def compare(xs: List[Int], ys: List[Int]): Boolean = xs match {
case Nil => true
case head :: tail if ys.forall(x => cmp(head, x)) => compare(tail, ys)
case _ => false
}

Scala, a cross between a foldLeft and a map supporting lazy evaluation

I have a collection which I want to map to a new collection, however each resulting value is dependent on the value before it in some way.I could solve this with a leftFold
val result:List[B] = (myList:List[A]).foldLeft(C -> List.empty[B]){
case ((c, list), a) =>
..some function returning something like..
C -> (B :: list)
}
The problem here is I need to iterate through the entire list to retrieve the resultant list. Say I wanted a function that maps TraversableOnce[A] to TraversableOnce[B] and only evaluate members as I call them?
It seems to me to be a fairly conventional problem so Im wondering if there is a common approach to this. What I currently have is:
implicit class TraversableOnceEx[T](val self : TraversableOnce[T]) extends AnyVal {
def foldyMappyFunction[A, U](a:A)(func:(A,T) => (A,U)):TraversableOnce[U] = {
var currentA = a
self.map { t =>
val result = func(currentA, t)
currentA = result._1
result._2
}
}
}
As far as functional purity goes, you couldn't run it in parallel, but otherwise it seems sound.
An example would be;
Return me each element and if it is the first time that element has appeared before.
val elements:TraversableOnce[E]
val result = elements.mappyFoldyFunction(Set.empty[E]) {
(s, e) => (s + e) -> (e -> s.contains(e))
}
result:TraversableOnce[(E,Boolean)]
You might be able to make use of the State Monad. Here is your example re-written using scalaz:
import scalaz._, Scalaz._
def foldyMappy(i: Int) = State[Set[Int], (Int, Boolean)](s => (s + i, (i, s contains(i))))
val r = List(1, 2, 3, 3, 6).traverseS(foldyMappy)(Set.empty[Int])._2
//List((1,false), (2,false), (3,false), (3,true), (6,false))
println(r)
It is look like you need SeqView. Use view or view(from: Int, until: Int) methods for create a non-strict view of list.
I really don't understand your example as your contains check will always result to false.
foldLeft is different. It will result in a single value by aggregating all elements of the list.
You clearly need map (List => List).
Anyway, answering your question about laziness:
you should use Stream instead of List. Stream doesn't evaluate the tail before actually calling it.
Stream API

Can't append to scala's mutable LinkedList?

I'm looking at the API and the :+ method returns a new LinkedList. The append method will only allow the appending of another linked list. The += method needs a var to work. Why would anyone ever need these if the LinkedList is mutable? What craziness is this?
If I had something like this in Java
final LinkedList myList = new LinkedList<String>();
mylist.add("balh");
How do I achieve the same thing in Scala?
If append can only take a LinkedList then why not use
mylist append LinkedList("something")
or
mylist append LinkedList(otherContainer: _*)
There is a reason for allowing only other LinkedLists in append, I think, because this guarantees the following:
l1 = LinkedList(1, 2, 3)
l2 = LinkedList(4)
l3 = LinkedList(5)
l1 append l2
// l1 == LinkedList(1, 2, 3, 4)
// l2 == LinkedList(4)
l2 append l3
// l1 == LinkedList(1, 2, 3, 4, 5)
// l2 == LinkedList(4, 5)
// l3 == LinkedList(5)
You can use a Buffer to build your values and convert it in the data structure using mapResult.
//Create a buffer which will build a linked list
val buf = new ArrayBuffer[String] mapResult { xs => LinkedList( xs:_* ) }
//You can append elements with +=, it is overriden to allow its use on a val
buf += "Something"
buf += "else"
//At the end you get your list
val lst = buf.result
// lst == LinkedList(Something, else)
Mutability is on the actual elements within the list and not on the structure that the list has (persistence). This is also stated in the scaladoc.
If returning a new List each time is not what you are after, and you cannot use var, you could always use the Java LinkedList.
val mylist = new java.util.LinkedList[String]
mylist add "something"
I'd stick with the Scala lists, if at all possible.
First, please pay more attention to the docs:
This class implements single linked lists where both the head (elem)
and the tail (next) are mutable.
So what it is giving you is mutable head and tail. These operations are represented through three methods:
append and insert change tail, so they receive a LinkedList as argument
update change the head of an element.
If you want a class that can grow, look at the classes extending Growable.