Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Compile and Execute Scala Online

object HelloWorld {
   def main(args: Array[String]) {
      
      println(sum((x=>x),1,3)
   }
   
  def sum(f: Int => Int)(a: Int, b: Int): Int = {
  def loop(a: Int, acc: Int): Int = {
    if (a > b) acc
    else loop(???, ???)
  }
  loop(a, 0)
}
}

Compile and Execute Scala Online

class Hello {

    def main(args: Array[String]) { 
        //var primeList = findPrimes(1, 10);
        println("End of Program");
    } 
    
    //start from the lowest value n and work up
    def findPrimes(n: Int, m: Int): Stream[Int] = {
        //gets all the values who's square are less than m, 
        //then for each, checks to see if those values % != 0
        lazy val primes: Stream[Int] = Stream.from(n, m).filter(i => primes.takeWhile(k => k*k <= i).forall(j => i % j != 0))
        primes.foreach(i => println(i))
        return primes
     }//end of findPrimes
}

PrimesBetween

object PrimesBetween {
   def main(args: Array[String]) {
      println("Hello, world!")
   }
}

Varargs

object varargsExample {
    //varargs and currying
    def method(arg1: Int*)(arg2: String*) = println(arg1, arg2)
    print("called with separate args: ") 
    method(1,2,3)("one")
    
    val l1 = List(3,3,4)
    print("called with sequence and with use of (_*): ")
    method(l1:_*)("one") 
    
    //partially applied function with varargs
    val method2 = method(1,2,3)_ 
    val list2 = List("hi","ho")
    print("partially applied function with varargs does NOT need _*: ")
    method2(list2)
    
    val l = List(4,5)
    method(l:_*)(list2:_*)
    
    def sum(xs: Int*) = xs.sum
    val summer = sum _
    val nums = List(1,2,3)
    println( summer(nums) )
}

Scala basics

object HelloWorld {
    def main(args:Array[String])
    {
  // VALUES are immutable constants. You can't change them once defined.
  val hello: String = "Namaste!"                     //> hello  : String = Hola!
  println(hello)                                  //> Hola!
  
  // Notice how Scala defines things backwards from other languages - you declare the
  // name, then the type.
  
  // VARIABLES are mutable
  var helloThere: String = hello                  //> helloThere  : String = Hola!
  helloThere = hello + " There!"
  println(helloThere)                             //> Hola! There!
  
  
  // One key objective of functional programming is to use immutable objects as often as possible.
  // Try to use operations that transform immutable objects into a new immutable object.
  // For example, we could have done the same thing like this:
  val immutableHelloThere = hello + "There!"      //> immutableHelloThere  : String = Hola!There!
  println(immutableHelloThere)                    //> Hola!There!
  
  // Some other types
  val numberOne : Int = 1                         //> numberOne  : Int = 1
  val truth  = false                      //> truth  : Boolean = true
  val letterA = 'R'                        //> letterA  : Char = a
  val pi : Double = 3.14159265                    //> pi  : Double = 3.14159265
  val piSinglePrecision : Float = 3.14159265f     //> piSinglePrecision  : Float = 3.1415927
  val bigNumber : Long = 1234567890l              //> bigNumber  : Long = 1234567890
  val smallNumber : Byte = 127                    //> smallNumber  : Byte = 127
  
  // String printing tricks
  // Concatenating stuff with +:
  println("Here is a mess: " + numberOne + truth + letterA + pi + bigNumber)
                                                  //> Here is a mess: 1truea3.141592651234567890
  
  // printf style:
  println(s"Pi is about $pi")  //> Pi is about 3.142
  println(s"Zero padding on the left: $bigNumber")
                                                  //> Zero padding on the left: 00001
                                                  
  // Substituting in variables:
  println(s"I can use the s prefix to use variables like $numberOne $truth $letterA")
                                                  //> I can use the s prefix to use variables like 1 true a
  // Substituting expressions (with curly brackets):
  println(s"The s prefix isn't limited to variables; I can include any expression. Like ${1+2}")
                                                  //> The s prefix isn't limited to variables; I can include any expression. Like
                                                  //|  3
                                                 
  // Using regular expressions:
  val theUltimateAnswer: String = "To life, the universe, and everything is 42."
                                                  //> theUltimateAnswer  : String = To life, the universe, and everything is 42.
                                                  //| 
  val pattern = """.* ([\d]+).*""".r              //> pattern  : scala.util.matching.Regex = .* ([\d]+).*
  val pattern(answerString) = theUltimateAnswer   //> answerString  : String = 42
  val answer = answerString.toInt                 //> answer  : Int = 42
  println(answer)                                 //> 42
  
  // Dealing with booleans
  val isGreater = 1 > 2                           //> isGreater  : Boolean = false
  val isLesser = 1 < 2                            //> isLesser  : Boolean = true
  val impossible = isGreater & isLesser           //> impossible  : Boolean = false
  val anotherWay = isGreater && isLesser          //> anotherWay  : Boolean = false
  
  val picard: String = "Picard"                   //> picard  : String = Picard
  val bestCaptain: String = "Picard"              //> bestCaptain  : String = Picard
  val isBest: Boolean = picard == bestCaptain     //> isBest  : Boolean = true
  
  // EXERCISE
  // Write some code that takes the value of pi, doubles it, and then prints it within a string with
  // three decimal places of precision to the right.
  // Just write your code below here; any time you save the file it will automatically display the results!
    }
}

test

object HelloWorld {
   def main(args: Array[String]) {
      println("Hello, world!")
   }
}

TereLiye

object HelloWorld {
   def main(args: Array[String]) {
      println("Hello, world!")
      val y = List(List(0.1, 0.4, 0.5),List(0.2, 0.8, 0.1),List(0.6, 0.9, 0.45))
      println(y)
      val maximum = max(flatten(y))
      val minimum = min(flatten(y))
      val z = multisplit(List(List(7,8,9,10,11,12)),Nil,3)
      val z2=join(List(List(1.0, 2.0, 3.0), List(4.0, 5.0, 6.0)),z,Nil)
      //println(z)
      //println(z2)
      
      println(join(List(List(1.0, 2.0), List(3.0, 4.0), List(6.0, 7.0)),List(List( 2.0), List(4.0), List(6.0,7.0)),Nil))
      val a=List(List(8.0, 2.0,3.0,4.0,5.0,6.0), List(7.0, 8.0,9.0,10.0,11.0,12.0), List(13.0, 14.0,15.0,16.0,17.0,18.0))
      println(multijoin(a,Nil,3,0))
      println(singlepooling(max,a,Nil,3))
        println(activationLayer(cube,List(List(3,2),List(3,4))))
   }
   
   
   def split(in:List[List[Double]],size:Int): List[List[Double]] = {
       if(in==Nil)
       Nil
       else
       {
        if(size == 0)
        in
        else
        {
           if(in.tail == Nil)
            split(List(List(in.head.head),in.head.tail),size-1)
           
           else
            split(List(in.head:::List(in.tail.head.head),flatten(in.tail).tail),size-1)
       }
       }
   }
   
  def multisplit(in:List[List[Double]],out:List[List[Double]],size:Int): List[List[Double]] = {
    if(in==List(List()))
    out
    else
    {
        val s=split(in,size)
        // if(split(in,size)==Nil)
        // out:::in
        // else
    multisplit(s.tail,out:::List(s.head),size)
    }
  }
  
  def join(l1:List[List[Double]],l2:List[List[Double]],l3:List[List[Double]]):List[List[Double]]= {
      if(l1==Nil && l2!=Nil)
      l2
      else if(l2==Nil && l1!=Nil)
      l1
      else if(l1==Nil && l2==Nil)
      l3
      else
      join(l1.tail,l2.tail,l3:::(List(l1.head:::l2.head)))
  }
  
  def multijoin(m:List[List[Double]],out:List[List[Double]],size:Int,count:Int):List[List[Double]] ={
      if(count==size)
      out
      else
      {
          val ms=multisplit(List(m.head),Nil,size)
          multijoin(m.tail,join(out,ms,Nil),size,count+1)
      }
      
  }
  
    
    // def splitmax(in:List[Int],out:List[Int],size:Int,count:Int): List[Int] ={
    //     if(count == 0)
    //         Nil
    //     else
    //     {
    //         splitmax(flatten((split(List(in),size)).tail),out:::List(max(split(List(in),size).head)),size,count-1)//count _ size
    //     }
    // }
  
//   def sphelper(poolingFunc:List[Double]=>Double,Image:List[List[Double]],out:List[List[Double]], k:Int,size:Int,count:Int):List[List[Double]] = {
//       if(count==(size/k))
//       out
//       else
//       sphelper(poolingFunc,Image.tail,out:::List(split(List(Image.head)).head))
//   }
   
   def singlepooling(poolingFunc:List[Double]=>Double,Image:List[List[Double]],out:List[Double], size:Int):List[Double] = {
       if(Image==Nil)
       out
       else
       {
       val mj = multijoin(Image,Nil,Image.size,0)
       singlepooling(poolingFunc,Image.tail,out:::List(poolingFunc(Image.head)),size)
       }
   }
   
   
   
   def cube(x: Double): Double = x * x * x
     
     def activationHelper(f: Double => Double, m: List[Double],out:List[Double]): List[Double] =
     {
         if(m==Nil)
         out
         else
         activationHelper(f,m.tail,out:::List(f(m.head)))
     }
     
     def activation(f: Double => Double, m: List[List[Double]],out: List[List[Double]]): List[List[Double]] =
     {
         if(m==Nil)
         out
         else
         {
             activation(f,m.tail,out:::List(activationHelper(f,m.head,Nil)))
         }
     }
     def activationLayer(f: Double => Double, m: List[List[Double]]): List[List[Double]] =
     {
         activation(f,m,Nil)
     }
     
     def max(xs: List[Double]): Double = {
    if(xs.tail.nonEmpty){
      val tl = max(xs.tail)
      if(tl > xs.head) tl
      else xs.head
    }else{
      xs.head
    }
  }
  
  def min(xs: List[Double]): Double = {
    if(xs.tail.nonEmpty){
      val tl = min(xs.tail)
      if(tl < xs.head) tl
      else xs.head
    }else{
      xs.head
    }
  }
   
      def flatten[A](list: List[List[A]]):List[A] = {
  if (list.length==0) List[A]() 
  else list.head ++ flatten(list.tail)
   }
   
   def normalizehelper(m:List[Double],out:List[Int],maxi:Double,mini:Double):List[Int] = {
       if(m==Nil)
       out
       else
       normalizehelper(m.tail,out:::List((scala.math.round((m.head-mini)/(maxi-mini)*255)).toInt),maxi,mini)
   }
   
   def normalize(m:List[List[Double]],out:List[List[Int]],maximum:Double,minimum:Double): List[List[Int]] = {
        if(m==Nil)
        out
        else
        {
            
        normalize(m.tail,out:::List((normalizehelper(m.head,Nil,maximum,minimum))),maximum,minimum)
        }
   }
   
}

PPL

package pplAssignment
/*
DONT EDIT THIS CODE. ANOTHER DRIVER WITH SIMILAR STRUCTURE WILL BE USED TO CHECK YOUR CODE
ONLY CHANGE <Student_ID> to Your ID
*/
object Driver{

  def main(args:Array[String]){
    val lines = scala.io.Source.fromFile(args(0), "utf-8").getLines.toList

    def getImage(iter:Int,index:Int):List[List[Double]]={
	    if(iter==index){
		    Nil	
	    }else{
		    lines(iter).split(' ').toList.map(_.toDouble)::getImage(iter+1,index)	
	    }
    }

    var curr=0
    val imagesize = lines(curr).split(' ').toList.map(_.toInt)
    var row=imagesize.head
    curr = curr+1
    val image:List[List[Double]]=getImage(curr,curr+row)
    curr = curr+row
    val kernel1size = lines(curr).split(' ').toList.map(_.toInt)
    row=kernel1size.head
    curr = curr+1
    val kernel1=getImage(curr,curr+row)
    curr = curr+row
    val kernel2size = lines(curr).split(' ').toList.map(_.toInt)
    row=kernel2size.head
    curr = curr+1
    val kernel2=getImage(curr,curr+row)
    curr = curr+row
    val kernel3size = lines(curr).split(' ').toList.map(_.toInt)
    row=kernel3size.head
    curr = curr+1
    val kernel3=getImage(curr,curr+row)
    curr = curr+row
    var l=lines(curr).split(' ').toList.map(_.toDouble)
    val w1=l.head
    l=l.tail
    val w2=l.head
    l=l.tail
    val b=l.head
    curr = curr+1
    val nmatsize= lines(curr).split(' ').toList.map(_.toInt)
    row=nmatsize.head
    curr = curr+1
    val nmat=getImage(curr,curr+row)
    curr = curr+row
    val poolmatsize= lines(curr).split(' ').toList.map(_.toInt)
    row=poolmatsize.head
    curr = curr+1
    val poolmat=getImage(curr,curr+row)
    curr = curr+row
    
    var size=lines(curr).split(' ').toList.map(_.toInt).head//Pooling size
    
    def max(xs: List[Double]): Double = {
    if(xs.tail.nonEmpty){
      val tl = max(xs.tail)
      if(tl > xs.head) tl
      else xs.head
    }else{
      xs.head
    }
  }

    //Dot product
    val res1=<F2015B5A70685P>.dotProduct(kernel1,kernel2)

    // println(prod)
    //convolution 
    val res2=<F2015B5A70685P>.convolute(image,kernel1,imagesize,kernel1size) 

    // println(result)

    //activation 
    val res3=<F2015B5A70685P>.activationLayer((x:Double)=>if(x>150) x else 0,image) 

    // println(result)

    //single pooling

    val res4=<F2015B5A70685P>.singlePooling(max,poolmat,size)
    //pooling

    val res5=<F2015B5A70685P>.poolingLayer(max,image,size) // max is a function

    //Normalize

    val res6=<F2015B5A70685P>.normalise(nmat) 

    //mixed layer

    val res7=<STUDENT_ID>.mixedLayer(image,kernel1,imagesize,kernel1size,(x:Double)=>x,max,size) // max is a function

    //assembly layer
    def time[R](block: => R): R = {
    val t0 = System.nanoTime()
    val result = block    // call-by-name
    val t1 = System.nanoTime()
    println("Elapsed time: " + (t1 - t0)/1000000000.0 + "s")
    result
}
// THIS COMMENTED SECTION CAN BE REMOVED TO TIME YOUR CODE. TOP LINE AFTER REMOVING THIS WILL BE YOUR TIMED OUTPUT. 
//  COMMENT NEXT LINE WHEN YOU UNCOMMENT THIS
// val res8=time{<STUDENT_ID>.assembly(image,imagesize,w1,w2,b,kernel1,kernel1size,kernel2,kernel2size,kernel3,kernel3size,size)}
    val res8=<F2015B5A70685P>.assembly(image,imagesize,w1,w2,b,kernel1,kernel1size,kernel2,kernel2size,kernel3,kernel3size,size)

    println("res1")
    println(res1)
    println("res2")
    println(res2)    
    println("res3")
    println(res3)    
    println("res4")
    println(res4)    
    println("res5")
    println(res5)    
    println("res6")
    println(res6)
    println("res7")
    println(res7)
    println("res8")
    println(res8)
    //}
  }
}

Compile and Execute Scala Online

object HelloWorld {
   def main(args: Array[String]) {
//      val a = 1 to 10
//      def func(x:Int):Int = {
//          return x*2
//      }
//      val b = func(2)
//      println(b)
//      val c = a.map(func)
//      println(c)
     
//     val d = func(_)
//     println(d(10))

 println("Pascal's Triangle")
 var n = 11
    for (row <- 0 to 10) {
      var a = " " * n
      print(a)
      n = n - 1
      for (col <- 0 to row) {
        print(pascal(col, row) + " ")
      }
      println()    
    
      
    }
  /**
  * Exercise 1: Pascal's Triangle
  */
  def pascal(c: Int, r: Int): Int = {
    if (c == 0 || c == r) 1
    else 
    pascal(c - 1, r - 1) + pascal(c, r - 1)
  }
  
  }
}

scala puzzle

object HelloWorld {
   def main(args: Array[String]) {
      val x = 123456789l
      val y=0f
      val z=x-(if(true){x} else{y})
      println(z)
   }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.