作者yzugsr (Bird)
看板Ruby
标题Re: [心得] 最大公约数
时间Tue Apr 26 00:39:07 2011
※ 引述《yzugsr (Bird)》之铭言:
: require 'rational' # Integer#gcd need this in ruby 1.8.7
: puts ARGV.map(&:to_i).inject(&:gcd)
: 推 SansWord:为什麽是functional programming style? 愿闻其详。 04/25 09:04
我觉得用上map, inject(fold)这些higher order function
而不用回圈及变数去记住运算的状态
是比较接近FP的写法....
当然这只是FP的一角而已,或许不能称为FP style
对於「将程式参数(argv)中的数字全部进行gcd运算」
参考一下Scala及Haskell可能的实作,结构跟上面的Ruby code会很相似
In Scala: (stdlib没有gcd,自干一下)
object Main {
def main(args: Array[String]) {
def gcd(a: Int, b: Int): Int = if (b==0) a else gcd(b, a%b)
println(args.map(_.toInt).reduceLeft(gcd))
}
}
In Haskell:
import System.Environment
main = do
argv <- getArgs
print $ foldl1 gcd $ map (read::String->Int) argv
啊....用Ruby写最短....冏....
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 123.204.180.162
1F:推 godfat:要比 ruby 短是很有难度的 XDD 04/27 21:22