功能编程:多边形的周长。

时间:2016-09-26 20:22:09

标签: scala functional-programming

我试图以功能的方式找到多边形的周长。我尽我所能,但我无法使其纯粹功能化。这是我的代码:

object Solution {

  def main(args: Array[String]) {
    var x:Double = 0
    val N = scala.io.StdIn.readInt
    val points = scala.io.Source.stdin.getLines().take(N).map(x=>x).toList
    for(i <- 0 to N-1){
      if(i==N-1) x+=dist(List(points(i),points(0)))
      else x += dist(List(points(i),points(i+1)))
    }
    println(x)
  }
  def dist(A: List[String]): Double = {
    scala.math.sqrt(scala.math.pow((A(0).split(" ")(0).toDouble-A(1).split(" ")(0).toDouble),2) + scala.math.pow((A(0).split(" ")(1).toDouble-A(1).split(" ")(1).toDouble),2))
  }
}

首先输入多边形的点数,然后在新行中输入每个点的笛卡尔坐标。

任何人都可以帮我把它变成纯粹的功能吗?

2 个答案:

答案 0 :(得分:2)

从分离问题开始:

// dist should just take 2 points
def dist(a: (Double,Double), b: (Double,Double)): Double = ...

// calculate perimeter
def perimeter (points: List[(Double,Double)]): Double = {
  // create a list of lines by connecting adjacent points
  val lines = points zip (points.tail ++ List(points.head))
  // aggregate the length of each line using foldLeft (/:)
  (0d /: lines)((acc, line) => acc ++ dist(line._1, line._2))
}

def main (args: Array[String]) {
  // main just needs to parse the lines
  val points = ... // parse the points

  println(perimeter(points))
}

答案 1 :(得分:0)

考虑val n = 5

val points = (1 to n).map(_ => Math.random * 10).toArray

和距离函数,例如

def dist(a: Double, b: Double) = math.abs(a-b)

然后在我们应用的{分组)点对n

上连续(圈数)dist次迭代
Iterator.continually(points)
        .flatten
        .sliding(2)
        .take(n)
        .map { case a :: b :: Nil => dist(a,b) }
        .sum