Scala Collections – FoldRight Method ”; Previous Next foldRight() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It navigates elements from Right to Left order. Syntax The following is the syntax of foldRight method. def foldRight[B](z: B)(op: (B, A) ? B): B Here, fold method takes associative binary operator function as a parameter. This method returns the resulted value. Usage Below is an example program of showing how to use foldRight method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3 ,4) //apply operation to get sum of all elements of the list val result = list.foldRight(0)(_ + _) //print result println(result) } } Here we”ve passed 0 as initial value to foldRight function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 10 Print Page Previous Next Advertisements ”;
Category: Computer Programming
Scala Collections – map
Scala Collections – Map Method ”; Previous Next map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection. Syntax The following is the syntax of map method. def map[B](f: (A) ? B): Traversable[B] Here, map method takes a prediate function as a parameter. This method returns the updated collection. Usage Below is an example program of showing how to use map method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3 ,4) //apply operation to get twice of each element. val result = list.map(_ * 2) //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(2, 4, 6, 8) Print Page Previous Next Advertisements ”;
Rust – Discussion
Discuss Rust ”; Previous Next Rust is a modern systems programming language developed by the Mozilla Corporation. It is intended to be a language for highly concurrent and highly secure systems. It compiles to native code; hence, it is blazingly fast like C and C++. This tutorial adopts a simple and practical approach to describe the concepts of Rust programming. Print Page Previous Next Advertisements ”;
Scala Collections – find
Scala Collections – Find Method ”; Previous Next find() method is method used by Iterators to find an element which satisfies a given predicate. Syntax The following is the syntax of find method. def find(p: (A) => Boolean): Option[A] Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the iterator. This method returns the Option element containing the matched element of iterator which satisfiles the given condition. Usage Below is an example program of showing how to use find method − Example object Demo { def main(args: Array[String]) = { val iterator = Iterator(3, 6, 9, 4, 2) //apply operation val result = iterator.find(x=>{x % 3 == 0}) //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Some(3) Print Page Previous Next Advertisements ”;
Scala Collections – DropWhile Method ”; Previous Next dropWhile() method is method used by List to drop all elements which satisfies a given condition. Syntax The following is the syntax of dropWhile method. def dropWhile(p: (A) => Boolean): List[A] Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list except dropped ones. Usage Below is an example program of showing how to use dropWhile method − Example object Demo { def main(args: Array[String]) = { val list = List(3, 6, 9, 4, 2) // print list println(list) //apply operation val result = list.dropWhile(x=>{x % 3 == 0}) //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(3, 6, 9, 4, 2) List(4, 2) Print Page Previous Next Advertisements ”;
Rust – Collections
Rust – Collections ”; Previous Next Rust”s standard collection library provides efficient implementations of the most common general-purpose programming data structures. This chapter discusses the implementation of the commonly used collections − Vector, HashMap and HashSet. Vector A Vector is a resizable array. It stores values in contiguous memory blocks. The predefined structure Vec can be used to create vectors. Some important features of a Vector are − A Vector can grow or shrink at runtime. A Vector is a homogeneous collection. A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4. A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack. Memory for a Vector is allocated in the heap. Syntax – Creating a Vector let mut instance_name = Vec::new(); The static method new() of the Vecstructure is used to create a vector instance. Alternatively, a vector can also be created using the vec! macro. The syntax is as given below − let vector_name = vec![val1,val2,val3] The following table lists some commonly used functions of the Vec structure. Sr.No Method Signature & Description 1 new() pub fn new()->Vect Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it. 2 push() pub fn push(&mut self, value: T) Appends an element to the back of a collection. 3 remove() pub fn remove(&mut self, index: usize) -> T Removes and returns the element at position index within the vector, shifting all elements after it to the left. 4 contains() pub fn contains(&self, x: &T) -> bool Returns true if the slice contains an element with the given value. 5 len() pub fn len(&self) -> usize Returns the number of elements in the vector, also referred to as its ”length”. Illustration: Creating a Vector – new() To create a vector, we use the static method new− fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); println!(“size of vector is :{}”,v.len()); println!(“{:?}”,v); } The above example creates a Vector using the static method new() that is defined in structure Vec. The push(val) function appends the value passed as parameter to the collection. The len() function returns the length of the vector. Output size of vector is :3 [20, 30, 40] Illustration: Creating a Vector – vec! Macro The following code creates a vector using the vec! macro. The data type of the vector is inferred the first value that is assigned to it. fn main() { let v = vec![1,2,3]; println!(“{:?}”,v); } Output [1, 2, 3] As mentioned earlier, a vector can only contain values of the same data type. The following snippet will throw a error[E0308]: mismatched types error. fn main() { let v = vec![1,2,3,”hello”]; println!(“{:?}”,v); } Illustration: push() Appends an element to the end of a collection. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); println!(“{:?}”,v); } Output [20, 30, 40] Illustration: remove() Removes and returns the element at position index within the vector, shifting all elements after it to the left. fn main() { let mut v = vec![10,20,30]; v.remove(1); println!(“{:?}”,v); } Output [10, 30] Illustration – contains() Returns true if the slice contains an element with the given value − fn main() { let v = vec![10,20,30]; if v.contains(&10) { println!(“found 10”); } println!(“{:?}”,v); } Output found 10 [10, 20, 30] Illustration: len() Returns the number of elements in the vector, also referred to as its ”length”. fn main() { let v = vec![1,2,3]; println!(“size of vector is :{}”,v.len()); } Output size of vector is :3 Accessing values from a Vector Individual elements in a vector can be accessed using their corresponding index numbers. The following example creates a vector ad prints the value of the first element. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); println!(“{:?}”,v[0]); } Output: `20` Values in a vector can also be fetched using reference to the collection. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); v.push(500); for i in &v { println!(“{}”,i); } println!(“{:?}”,v); } Output 20 30 40 500 [20, 30, 40, 500] HashMap A map is a collection of key-value pairs (called entries). No two entries in a map can have the same key. In short, a map is a lookup table. A HashMap stores the keys and values in a hash table. The entries are stored in an arbitrary order. The key is used to search for values in the HashMap. The HashMap structure is defined in the std::collections module. This module should be explicitly imported to access the HashMap structure. Syntax: Creating a HashMap let mut instance_name = HashMap::new(); The static method new() of the HashMap structure is used to create a HashMap object. This method creates an empty HashMap. The commonly used functions of HashMap are discussed below − Sr.No Method Signature & Description 1 insert() pub fn insert(&mut self, k: K, v: V) -> Option Inserts a key/value pair, if no key then None is returned. After update, old value is returned. 2 len() pub fn len(&self) -> usize Returns the number of elements in the map. 3 get() pub fn get<Q: ?Sized>(&lself, k: &Q) -> Option<&V> where K:Borrow Q:Hash+ Eq Returns a reference to the value corresponding to the key. 4 iter() pub fn iter(&self) -> Iter<K, V> An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&”a K, &”a V). 5 contains_key pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool Returns true if the map contains a value for the specified key. 6 remove() pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> Removes a key from the map, returning
Scala Collections – flatten
Scala Collections – Flatten Method ”; Previous Next flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections. Syntax The following is the syntax of flatten method. def flatten[B]: Traversable[B] Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition. Usage Below is an example program of showing how to use flatten method − Example object Demo { def main(args: Array[String]) = { val list = List(List(1,2), List(3,4)) //apply operation val result = list.flatten //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(1, 2, 3, 4) Print Page Previous Next Advertisements ”;
Scala Collections – Multi-Dimensional Array ”; Previous Next There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays. The following is the example of defining a two-dimensional array − var myMatrix = ofDim[Int](3,3) This is an array that has three elements each being an array of integers that has three elements. Try the following example program to process a multi-dimensional array − Example import Array._ object Demo { def main(args: Array[String]) { var myMatrix = ofDim[Int](3,3) // build a matrix for (i <- 0 to 2) { for ( j <- 0 to 2) { myMatrix(i)(j) = j; } } // Print two dimensional array for (i <- 0 to 2) { for ( j <- 0 to 2) { print(” ” + myMatrix(i)(j)); } println(); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 0 1 2 0 1 2 0 1 2 Print Page Previous Next Advertisements ”;
Scala Collections – Useful Resources ”; Previous Next The following resources contain additional information on Scala. Please use them to get more in-depth knowledge on this topic. Useful Links on Scala The Scala Programming Language − All the information required to start writing programs in Scala! Contains manuals, a tour of Scala, information on the available Scala books, many guides, and useful documentation resources. Standard scaladoc Scala API − Browse the online API documentation generated by using our standard scaladoc tool. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition. Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Scala To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Scala Collections – drop
Scala Collections – Drop Method ”; Previous Next drop() method is method used by List to select all elements except first n elements of the list. Syntax The following is the syntax of drop method. def drop(n: Int): List[A] Here, n is the number of elements to be dropped from the list. This method returns the all the elements of list except first n ones. Usage Below is an example program of showing how to use drop method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3, 4, 5) // print list println(list) //apply operation val result = list.drop(3) //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(1, 2, 3, 4, 5) List(4, 5) Print Page Previous Next Advertisements ”;