zoukankan      html  css  js  c++  java
  • Scala学习笔记(七):Rational、隐式转换、偏函数、闭包、重复参数及柯里化

    class Rational(n: Int, d: Int) {
      require(d != 0)
      private val g: Int = gcd(n, d)
    
      val number: Int = n / g
      val denom: Int = d / g
    
      def this(n: Int) = this(n, 1)
    
      override def toString: String =
        if (denom != 1) number + "/" + denom else number.toString
    
      def add(that: Rational): Rational = {
        new Rational(number * that.denom + denom * that.number, denom * that.denom)
      }
    
      def +(x: Int): Rational = {
        add(new Rational(x))
      }
    
      def +(that: Rational): Rational = add(that)
    
      private def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
      }
    
    }
    
    object Rational extends App {
      val rational1: Rational = new Rational(1, 2)
      val rational2: Rational = new Rational(1, 2)
      val add: Rational = rational1 + rational2
      println(s"add=======>$add")
    
      //隐式转换
      implicit def intToRational(x: Int): Rational = new Rational(x)
    
      println("Int*Iational===>" + 2 + intToRational(2))
      //偏函数
      val sum = (x: Int, y: Int, z: Int) => x + y + z
      val b = sum(1, _: Int, 3)
    
      println(b(1))
      //闭包
      val more = 1
      val offset = (x: Int) => x + more
    
      //重复参数
      def echo(s: String*): Unit = s.foreach(println)
    
      echo("a", "b")
    
      //柯里化
      def curriedSum(x: Int)(y: Int) = x + y
    
      val add1 = (x: Int) => curriedSum(1) _
      println(add1)
    }
    
  • 相关阅读:
    第二章 成员、变量和常量
    Roman To Integer
    Integer To Roman
    Container With Most Water
    搜狗2015前端工程师笔试题
    从网易与淘宝的font-size思考前端设计稿与工作流
    移动端web app自适应布局探索与总结
    CSS 常用代码
    利用 HTML 和 CSS 实现常见的布局
    CSS 尺寸单位
  • 原文地址:https://www.cnblogs.com/yw0219/p/10146611.html
Copyright © 2011-2022 走看看