const的目的是什么

const的目的是什么

本文介绍了Function.const的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它位于但没有太多文档。它似乎总是返回第一个参数。



Function.const(1)(2)例如返回 1



为什么它存在,为什么它有用?为了给出更理论上的答案:const是。当你使用相当抽象的概念时,有时候它会弹出,而你没有太多的工作。考虑一个(Haskell风格)Functor特性:

$ $ p $ $ $ $ ,B](f:A => B,fa:F [A]):F [B]
//(<$)Haskell
def left [A,B](a :A,fb:F [B]):F [A]
}

现在fmap需要是抽象的,因为它是仿函数的本质。但是我们可以写一个左边的一般实现,这里我们需要const:

  trait Functor [F [_]] {
def fmap [A​​,B](f:A => B,fa:F [A]):F [B]
//(<$)Haskell
def left [A,B](a:A,fb:F [B]):F [A] =
fmap(Function.const(a),fb)
}

测试选项:

  case对象OptionFunctor扩展Functor [Option] {
def fmap [A​​,B](f:A => B,fa:Option [A]):Option [B] = fa match {
case一些(a)=>一些(f(a))
案例无=>无
}
}

//剩下的工作:
OptionFunctor.left(test,Some(42))
// - > ; Option [java.lang.String] =一些(测试)
OptionFunctor.left(test,None:Option [Int])
// - > Option [java.lang.String] = None

正如你所看到的,当我们在第二个参数中已经有了一个角色模型或者这个仿函数的模式时,在某个仿函数中的一个值)。定义它非常抽象而不知道任何关于函子的种类只能通过使用const。


It is in ScalaDoc but without much documentation. It seems that it always returns the first parameter.

Function.const(1)(2) for instance returns 1.

Why does it exist and why is it useful?

解决方案

To give a more theoretical answer: const is the K combinator of the SKI calculus. It pops sometimes up when you work with quite abstract concepts where you don't have much "to work with". Consider a (Haskell style) Functor trait:

trait Functor[F[_]] {
   def fmap[A,B](f:A=>B, fa: F[A]):F[B]
   //(<$) in Haskell
   def left[A,B](a:A, fb:F[B]):F[A]
}

Now fmap needs to be abstract, as it is the very essence of a functor. But we can write a general implementation of left, and here we need const:

trait Functor[F[_]] {
   def fmap[A,B](f:A=>B, fa: F[A]):F[B]
   //(<$) in Haskell
   def left[A,B](a:A, fb:F[B]):F[A] =
     fmap(Function.const(a), fb)
}

Test with Option:

case object OptionFunctor extends Functor[Option] {
   def fmap[A,B] (f:A=>B, fa:Option[A]):Option[B] = fa match {
      case Some(a) => Some(f(a))
      case None => None
   }
}

//left works:
OptionFunctor.left("test",Some(42))
//--> Option[java.lang.String] = Some(test)
OptionFunctor.left("test",None:Option[Int])
//--> Option[java.lang.String] = None

As you can see left does what it should (wrapping a value in some functor when we have already a "role model" or "pattern" for this functor in the second argument). Defining it very abstract without knowing anything about the kind of functor was only possible by using const.

这篇关于Function.const的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:36