身份功能在哪里以及为什么有用? [英] Where and why is identity function useful?

查看:110
本文介绍了身份功能在哪里以及为什么有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白为什么功能组成很重要。它允许从小而简单的构建大型复杂的函数。

 
val f:A => B = ...
val g:B => C = ...

val h = f and Then g; //构成f和g

此构图符合 identity associativity 定律



Associativity 非常有用,因为它允许将 f1和then f2和then f3分组,然后f4 ... 以任意顺序。现在我想知道为什么 identity 是有用的。

 
def f [T](t:T)= t / /身份函数
val g:A => B = ... //任何函数
g和Then f [B] == f [A]然后g

所以,我的问题是在哪里以及为什么这个 identity 有用。

解决方案

只要接口提供了比实际需要更多的控制权,身份就很有用。例如,或者都没有 flatten 方法。假设您有

$ $ p $ val e:[Double,Float] = Right(1.0f)

,并且您想将其平铺为 Double 。你怎么做呢?有一个方便的 fold 方法,但没有方法将右侧转换为左侧的类型。所以你

  e.fold(identity,_.toDouble)

,你就得到了你想要的。


I understand why function composition is important. It allows building large and complex functions from small and simple ones.

val f: A => B = ...
val g: B => C = ...

val h = f andThen g; // compose f and g

This composition conforms to identity and associativity laws.

Associativity is useful because it allows grouping f1 andThen f2 andThen f3 andThen f4 ... in any order. Now I wonder why identity is useful.

def f[T](t:T) = t   // identity function
val g: A => B = ... // just any function
g andThen f[B] == f[A] andThen g 

So, my question is where and why this identity useful.

解决方案

Identity is useful whenever an interface gives you more control than you actually need. For example, Either has no flatten method. Let's suppose you have

val e: Either[Double, Float] = Right(1.0f)

and you want to flatten it to a Double. How do you do it? There is a handy fold method, but no method to convert the right side to the left side's type. So you

e.fold(identity, _.toDouble)

and you've got what you want.

这篇关于身份功能在哪里以及为什么有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆