计算面积 - Erlang

时间:2017-11-02 16:17:16

标签: list erlang area

我有以下功能,应使用列表中的每个值计算一个区域。

我遇到的问题是该函数只打印列表中第一个项目的第一个结果,以及我需要为列表中的每个项目打印的内容。

您可以认为列表中的每个项目都是一个案例,我想打印所有案例。

object box {

  trait Transform[A, B] {
    def apply(in: A): B
  }
  object Transform {
    def instance[A, B](f: A => B): Transform[A, B] = new Transform[A, B] {
      override def apply(in: A): B = f(in)
    }
  }

  implicit class TransformOps[T](w: T) {
    def transform(implicit t: Transform[T, String]) = t(w)
  }

  trait ShadowedOperation {
    type I
    type O
    def param: String
    def otherParam: Int
    def in: I
    def out: O
  }

  object ShadowedOperation {
    // How can i do this in a generic, typed and wonderful way ???
    implicit def operationToString: Transform[ShadowedOperation, String] = ???
  }

  case class Operation[I0, O0](
    param: String,
    otherParam: Int,
    in: I0,
    out: O0
  ) extends ShadowedOperation {type I = I0; type O = O0}

  object Operation {
    implicit def operationToString[I, O](
      implicit
      iToString: Transform[I, String],
      oToString: Transform[O, String]
    ): Transform[Operation[I, O], String] =
      Transform.instance(in => s"${in.otherParam} - ${in.param} - ${iToString(in.in)} - ${oToString(in.out)}")
  }

  def fakeParseFromString(in: String): List[ShadowedOperation] = {
    // this simulate a parsing (or read from db) from string to extract the case class
    List(Operation("param", 0, "in!", "out!"), Operation("param", 0, "in!", 100))
  }

}


object Main extends App {

  import box._

  implicit val intToString: Transform[Int, String] = Transform.instance(_.toString)
  implicit val stringToString: Transform[String, String] = Transform.instance(_.toString)

  val op = Operation("param", 0, "in!", "out!")
  val shadowedOperationList = fakeParseFromString("imagine that this string contain a json")
  val opString = op.transform
  val shadowedOpString = shadowedOperationList.map(_.transform)
  println(opString)
  println(shadowedOpString)
}

1 个答案:

答案 0 :(得分:4)

你的递归错了。应该做的是打印头部区域,然后递归尾部。您还需要添加一个基本案例,处理空列表。

area([]) -> ok;
area([H|T]) ->
  io:format("~p~n", [(math:sqrt(3.0) * (H*H)) - (3.14 * (H*H))/2]),
  area(T).

如果你想要一个区域列表作为结果,你可以这样做:

area([]) -> [];
area([H|T]) ->
  [(math:sqrt(3.0) * (H*H)) - (3.14 * (H*H))/2 | area(T)].