Scala 编程中分而治之的思想 (divide and conquer)

一种思想:

把系统分成最简单的状态,处理它,迭代它

两种套路:

1 使用head tail:

思想即使:

情况1:如果当前list为空,怎么处理

情况2:如果当前情况为非空,即有head和非空队列tail。这种情况处理  是使用递归调用tail的结果(假定除了head以外其他的数据都处理好了) 和 head进行某种操作。


2 使用merge

思想:

1 把List分为两个部分,first ,second

2 fist进行某种操作,second行某种操作

3 把两者merge在一起


代码胜过雄辩,比如对于一个List进行排序:

思想1:

def isort(xs: List[Int]): List[Int] = xs match {
case List() => List()
case x :: xs1 => insert(x, isort(xs1))
}
def insert(x: Int, xs: List[Int]): List[Int] = xs match {
case List() => List(x)
case y :: ys => if (x <= y) x :: xs
else y :: insert(x, ys)
}


思想2:

def msort[T](less: (T, T) => Boolean)
(xs: List[T]): List[T] = {
def merge(xs: List[T], ys: List[T]): List[T] =
(xs, ys) match {
case (Nil, _) => ys
case (_, Nil) => xs
case (x :: xs1, y :: ys1) =>
if (less(x, y)) x :: merge(xs1, ys)
else y :: merge(xs, ys1)
}
val n = xs.length / 2
if (n == 0) xs
else {
val (ys, zs) = xs splitAt n
merge(msort(less)(ys), msort(less)(zs))
}
}


注明:

使用了curry函数式编程思想(多参数),非常简单实现依赖注入,比如依赖比较规则




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值