scala作业4

1、编写函数values(fun:(Int)=>Int,low:Int,high:Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。比如,values(x=>x*x,-5,5)应该产出一个对偶的集合(-5,25),(-4,16),(-3,9),…,(5,25) 。
package classDemo
object Hry_Test {
  def values(fun: (Int) => Int, low: Int, high: Int) = {
    val result = (low to high).map(
      p => {
        (p, fun(p))
      }
    );
    result
  }
  def fun(x: Int) = {
    x * x
  }
  def main(args: Array[String]): Unit = {
  //循环打印
    values(fun, -5, 5).foreach(item => {
      println("("+item._1+","+item._2+")")
    })
   //println(values(x=>x*x,5,5).mkString(","))//打印一行
  }
}
结果:
(-5,25)
(-4,16)
(-3,9)
(-2,4)
(-1,1)
(0,0)
(1,1)
(2,4)
(3,9)
(4,16)
(5,25)
2、如何用reduceLeft得到数组中的最大元素? 
package classDemo
object Hry_Test {
  def main(args: Array[String]): Unit = {
    val arr1=Array(1,2,4,6,4,3,2,7,4,6,8,9,53,23)
    val arr2=arr1.reduceLeft((n1, n2) => {
      if (n1 > n2) {
        n1
      } else {
        n2
      }
    })
    println(arr2)
  }
}
3、用to和reduceLeft实现阶乘函数,不得使用循环或递归 
解题思路:注意0的阶层也是1
package classDemo
object Hry_Test {
  def getMsg(n2:Int)=
  {
    val arr=1 to n2
    var arr1=1
    if(n2==0)
     {
       arr1=1
     }
    else
    {
      arr1=arr.reduceLeft((_*_))
    }
    println(s"$n2!=$arr1")
  }
  def main(args: Array[String]): Unit = {
    getMsg(0)
    getMsg(1)
    getMsg(5)
  }
}
结果:
0!=1
1!=1
5!=120
4、编写函数largest(fun:(Int)=>Int,inputs:Seq[Int]),输出在给定输入序列中给定函数的最大值。举例来说,largest(x=>10x-xx,1 to 10)应该返回2
package classDemo
object Hry_Test {
  def largest(fun:(Int)=>Int,inputs:Seq[Int]): Unit ={
    val result = inputs.map(fun(_)).max;
    println(s"10*x-x*x函数$inputs 区间之内的最大值是:$result")
  }
  def fun(x: Int) = {
    10 * x-x*x
  }
  def main(args: Array[String]): Unit = {
    (largest(x => 10 * x - x*x, 1 to 10))
  }
}
结果:
10*x-x*x函数Range 1 to 10 区间之内的最大值是:25
5、利用隐式转换为java.io.File类加上read方法读取文件中的内容。 
package classDemo
import java.io.File
import scala.io.Source
class File1(filename:File) {
  def read = Source.fromFile(filename).mkString.split(" ")
}
object TestFile
{
  //隐式转换方法
  implicit def myFR(filename:File)=new File1(filename)
  //隐式转换参数
  def myFileRead2(filename: File)(implicit file: File => File1): Unit =
  {
    filename.read
  }
}
object Hry_Test {
  def main(args: Array[String]): Unit = {
    import TestFile._
    println(new File("c://words.txt").read)
  }
}
6、利用隐式类完成5中的要求。
package classDemo
import java.io.File
import scala.io.Source
class File1(filename:File) {
def read = Source.fromFile(filename).mkString.split(" ")
}
object TestFile1
{
  //隐式转换类
  implicit class MyFR(f: File) {
    def read = Source.fromFile(f).mkString
  }
}
object Hry_Test {
  def main(args: Array[String]): Unit = {
    import  TestFile1.MyFR
    println(new File1("c://words.txt").read)
  }
}





   

猜你喜欢

转载自blog.csdn.net/weixin_43562705/article/details/91437958
今日推荐