Scala 函数式编程中的高阶函数练习

Scala 函数式编程中的高阶函数练习

  • 编写一个 compose 函数,将两个类型为 Double=>Option[Double]的函数组合在一起,产生另一个同样类型的函数。如果其中一个函数返回 None,则组合函数也应返回 None。例如:
def f(x : Double) = if ( x >= 0) Some(sqrt(x)) else None
def g(x : Double) = if ( x != 1) Some( 1 / ( x - 1)) else None
val h = compose(f,g)
  • h(2)将得到 Some(1),而 h(1)和 h(0)将得到 None
def compose(f:Double=>Option[Double],g:Double=>Option[Double])={
(x : Double) =>
if (f(x) == None || g(x) == None) None
else g(x)
}
import scala.math.sqrt
def f(x : Double) = if ( x >= 0) Some(sqrt(x)) else None
def g(x : Double) = if ( x != 1) Some( 1 / ( x - 1)) else None
val h = compose(f,g)
println(h(2))
  • 编写函数 values(fun:(Int)=>Int,low:Int,high:Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。比如, values(x=>x*x,-5,5)应该产出一个对偶的集合(-5,25),(-4,16),(-3,9),…,(5,25)
def values(fun:(Int)=>Int,low:Int,high:Int) ={
var array = List[(Int,Int)]()
low to high foreach {
x =>
array = (x, fun(x)) :: array
}
array
}
println(values(x => x * x, -5, 5).mkString)
  • 如何用 reduceLeft 得到数组 Array(1,333,4,6,4,4,9,32,6,9,0,2)中的最大元素?
val arr = Array(1,333,4,6,4,4,9,32,6,9,0,2)
print(arr.reduceLeft((l,r)=>if(l>=r) l else r))
  • toreduceLeft 实现阶乘函数,不得使用循环或递归
def factorial(n:Int): Unit ={
1 to n reduceLeft(_ * _)
}
  • 编写函数 largest(fun:(Int)=>Int,inputs:Seq[Int]),输出在给定输入序列中给定函数的最大值。举例来说, largest(x=>10x-xx,1 to 10)应该返回 25.不得使用循环或递归
def largest1(fun:(Int)=>Int, inputs:Seq[Int]) = inputs.foldLeft(1)((a,b)=>
if(fun(b)>a) fun(b) else a)
def largest2(fun:(Int)=>Int, inputs:Seq[Int]) = inputs.map(fun(_)).max
println(largest1(x => 10 * x - x * x, 1 to 10))
println(largest2(x => 10 * x - x * x, 1 to 10))
  • 要得到一个序列的对偶很容易,比如
val pairs = (1 to 10) zip (11 to 20)
  • 编写函数 adjustToPair,该函数接受一个类型为(Int,Int)=>Int 的函数作为参数,并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_*_)((6,7))应得到 42。然后用这个函数通过 map 计算出各个对偶的元素之和
def ajustToPair(fun: (Int, Int) => Int) = (x: (Int, Int)) => fun(x._1, x._2)
val x = ajustToPair(_ * _)((6, 7))
println(x)
val pairs = (1 to 10) zip (11 to 20)
println(pairs)
val y = pairs.map(ajustToPair(_ + _))
println(y)
  • 实现一个 unless 控制抽象,工作机制类似 if,但条件是反过来的。
def unless(condition: => Boolean)(block: => Unit) { if (!condition) { block } }
unless (0 > 1) { println("Unless!") }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值