week1的第三题体现出函数式语言的优美

94 views
Skip to first unread message

Zang MingJie

unread,
Oct 8, 2012, 4:16:59 AM10/8/12
to sca...@googlegroups.com
递归+一个mapreduce就搞定了

  def countChange(money: Int, coins: List[Int]): Int = if (coins.isEmpty) {
    if (money == 0) 1 else 0
  } else {
    val cur = coins.head
    (0 /: ((0 to (money / cur)) map { i => countChange(money - i * cur, coins.tail) })) { _ + _ }
  }

颜发明

unread,
Oct 10, 2012, 3:37:00 AM10/10/12
to sca...@googlegroups.com
我在这题上悲催了。绞尽脑汁也想不出一个好的递归方式,最后不伦不类地拼凑了一个既有递归又有while循环和var变量的怪异混合体,结果没问题,但是很丑陋的说。
经由这一道一道的题目,慢慢地体会函数式的思想,现在找到一点点感觉了,小小进步中……


在 2012年10月8日星期一UTC+8下午4时16分59秒,Zang MingJie写道:

Lurga Lee

unread,
Oct 18, 2012, 9:32:08 PM10/18/12
to sca...@googlegroups.com
这不是尾递归,在实际运行时很危险。昨天翻到个不错的文章【1】,十五章到十九章很好的解释了老师不停强调的递归和list(2,3,4,5课都能看到它的影子)
【1】http://buaawhl.iteye.com/blog/1160327 

2012/10/19 Cheng CHI <clou...@gmail.com>
最后的else里这样就可以了…… 不过前边也有一点点点不同…… (不直接发全部代码了@。@

  countChange(money, coins.tail) + countChange(money-coins.head, coins)
--
您收到此邮件是因为您订阅了 Google 网上论坛的“Scala中文社区”论坛。
要向此网上论坛发帖,请发送电子邮件至 sca...@googlegroups.com
 
 

杨博

unread,
Oct 19, 2012, 8:26:48 AM10/19/12
to sca...@googlegroups.com
你这代码不符合Scala编码规范(http://docs.scala-lang.org/style/method-invocation.html):
Finally, the use of the /: and :\ should be avoided in preference to the more explicit foldLeftand foldRight method of Iterator. The right-associativity of the /: can lead to extremely confusing code, at the benefit of saving a few characters.

在 2012年10月8日星期一UTC+8下午4时16分59秒,Zang MingJie写道:
Reply all
Reply to author
Forward
0 new messages