• learning scala Function Composition andThen


    • Ordering using andThenf(x) andThen g(x) = g(f(x))
    • Ordering using composef(x) compose g(x) = f(g(x))
     println("Step 1: Assume a pre-calculated total cost amount")
      val totalCost: Double = 10
    
    
    
      println("
    Step 2: How to define a val function to apply discount to total cost")
      val applyDiscountValFunction = (amount: Double) => {
        println("Apply discount function")
        val discount = 2 // fetch discount from database
        amount - discount
      }
    
    
    
      println("
    Step 3: How to call a val function")
      println(s"Total cost of 5 donuts with discount = ${applyDiscountValFunction(totalCost)}")
    
    
    
      println("
    Step 4: How to define a val function to apply tax to total cost")
      val applyTaxValFunction = (amount: Double) => {
        println("Apply tax function")
        val tax = 1 // fetch tax from database
        amount + tax
      }
    
    
    
      println("
    Step 5: How to call andThen on a val function")
      println(s"Total cost of 5 donuts = ${ (applyDiscountValFunction andThen applyTaxValFunction)(totalCost) }")

    result:

    Step 1: Assume a pre-calculated total cost amount
    
    Step 2: How to define a val function to apply discount to total cost
    
    Step 3: How to call a val function
    Apply discount function
    Total cost of 5 donuts with discount = 8
    
    Step 4: How to define a val function to apply tax to total cost
    
    Step 5: How to call andThen on a val function
    Apply discount function
    Apply tax function
    Total cost of 5 donuts = 9
  • 相关阅读:
    linux 常用命令
    ubuntu 安装在硬盘与配置
    linux管道符、重定向与环境变量
    linux用户身份与文件权限
    centos开启ftp服务
    js实现常见排序算法
    算法分析
    Vim
    CSS的3种使用方法
    cookie 在登录时的存储,获取,清除
  • 原文地址:https://www.cnblogs.com/lianghong881018/p/11174269.html
Copyright © 2020-2023  润新知