Scalaz(6)- typeclass:Functor-just map

2024-04-09 05:08
文章标签 map functor scalaz typeclass

本文主要是介绍Scalaz(6)- typeclass:Functor-just map,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  Functor是范畴学(Category theory)里的概念。不过无须担心,我们在scala FP编程里并不需要先掌握范畴学知识的。在scalaz里,Functor就是一个普通的typeclass,具备map over特性。我的理解中,Functor的主要用途是在FP过程中更新包嵌在容器(高阶类)F[T]中元素T值。典型例子如:List[String], Option[Int]等。我们曾经介绍过FP与OOP的其中一项典型区别在于FP会尽量避免中间变量(temp variables)。FP的变量V是以F[V]这种形式存在的,如:List[Int]里一个Int变量是包嵌在容器List里的。所以FP需要特殊的方式来更新变量V,这就是Functor map over的意思。scalaz提供了Functor typeclass不但使用户能map over自定义的高阶类型F[T],并且用户通过提供自定义类型的Functor实例就可以免费使用scalaz Functor typeclass提供的一系列组件函数(combinator functions)。

  scalaz中Functor的trait是这样定义的:scalaz/Functor.scala

trait Functor[F[_]] extends InvariantFunctor[F] { self =>import Liskov.<~</** Lift `f` into `F` and apply to `F[A]`. */def map[A, B](fa: F[A])(f: A => B): F[B]...

任何类型的实例只需要实现这个抽象函数map就可以使用scalaz Functor typeclass的这些注入方法了:scalaz/syntax/FunctorSyntax.scala

final class FunctorOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Functor[F]) extends Ops[F[A]] {import Leibniz.===import Liskov.<~<final def map[B](f: A => B): F[B] = F.map(self)(f)final def distribute[G[_], B](f: A => G[B])(implicit D: Distributive[G]): G[F[B]] = D.distribute(self)(f)final def cosequence[G[_], B](implicit ev: A === G[B], D: Distributive[G]): G[F[B]] = D.distribute(self)(ev(_))final def cotraverse[G[_], B, C](f: F[B] => C)(implicit ev: A === G[B], D: Distributive[G]): G[C] = D.map(cosequence)(f)final def ∘[B](f: A => B): F[B] = F.map(self)(f)final def strengthL[B](b: B): F[(B, A)] = F.strengthL(b, self)final def strengthR[B](b: B): F[(A, B)] = F.strengthR(self, b)final def fpair: F[(A, A)] = F.fpair(self)final def fproduct[B](f: A => B): F[(A, B)] = F.fproduct(self)(f)final def void: F[Unit] = F.void(self)final def fpoint[G[_]: Applicative]: F[G[A]] = F.map(self)(a => Applicative[G].point(a))final def >|[B](b: => B): F[B] = F.map(self)(_ => b)final def as[B](b: => B): F[B] = F.map(self)(_ => b)final def widen[B](implicit ev: A <~< B): F[B] = F.widen(self)}

以上的注入方法中除了map外其它方法的应用场景我还没有确切的想法,不过这不会妨碍我们示范它们的用法。Functor必须遵循一些定律:

1、map(fa)(x => x) === fa

2、map(map(fa)(f1))(f2) === map(fa)(f2 compose f1)

scalaz/Functor.scala

  trait FunctorLaw extends InvariantFunctorLaw {/** The identity function, lifted, is a no-op. map(fa)(x => x*/def identity[A](fa: F[A])(implicit FA: Equal[F[A]]): Boolean = FA.equal(map(fa)(x => x), fa)/*** A series of maps may be freely rewritten as a single map on a* composed function.*/def composite[A, B, C](fa: F[A], f1: A => B, f2: B => C)(implicit FC: Equal[F[C]]): Boolean = FC.equal(map(map(fa)(f1))(f2), map(fa)(f2 compose f1))}

我们可以用List来证明:map(fa)(x => x) === fa

scala> List(1,2,3).map(x => x) assert_=== List(1,2,3)scala> List(1,2,3).map(identity) assert_=== List(1,2)
java.lang.RuntimeException: [1,2,3] ≠ [1,2]at scala.sys.package$.error(package.scala:27)at scalaz.syntax.EqualOps.assert_$eq$eq$eq(EqualSyntax.scala:16)... 43 elided

map(map(fa)(f1))(f2) === map(fa)(f2 compose f1)

scala> Functor[List].map(List(1,2,3).map(i => i + 1))(i2 => i2 * 3) assert_=== List(1,2,3).map(((i2:Int) => i2 * 3) compose ((i:Int) => i + 1))scala> Functor[List].map(List(1,2,3).map(i => i + 1))(i2 => i2 * 3) assert_=== List(1,2,3).map(((i:Int) => i + 1) compose ((i2:Int) => i2 * 3))
java.lang.RuntimeException: [6,9,12] ≠ [4,7,10]at scala.sys.package$.error(package.scala:27)at scalaz.syntax.EqualOps.assert_$eq$eq$eq(EqualSyntax.scala:16)... 43 elided

注意:compose对f1,f2的施用是互换的。

针对我们自定义的类型,我们只要实现map函数就可以得到这个类型的Functor实例。一旦实现了这个类型的Functor实例,我们就可以使用以上scalaz提供的所有Functor组件函数了。

我们先试着创建一个类型然后推算它的Functor实例:

case class Item3[A](i1: A, i2: A, i3: A)
val item3Functor = new Functor[Item3] {def map[A,B](ia: Item3[A])(f: A => B): Item3[B] = Item3(f(ia.i1),f(ia.i2),f(ia.i3))
}                                                 //> item3Functor  : scalaz.Functor[scalaz.functor.Item3] = scalaz.functor$$anonf//| un$main$1$$anon$1@5e265ba4

scalaz同时在scalaz-tests下提供了一套scalacheck测试库。我们可以对Item3的Functor实例进行测试:

scala> functor.laws[Item3].check
<console>:27: error: could not find implicit value for parameter af: org.scalacheck.Arbitrary[Item3[Int]]functor.laws[Item3].check^

看来我们需要提供自定义类型Item3的随意产生器(Generator):

scala> implicit def item3Arbi[A](implicit a: Arbitrary[A]): Arbitrary[Item3[A]] = Arbitrary {| def genItem3: Gen[Item3[A]]  = for {| b <- Arbitrary.arbitrary[A]| c <- Arbitrary.arbitrary[A]| d <- Arbitrary.arbitrary[A]| } yield Item3(b,c,d)| genItem3| }
item3Arbi: [A](implicit a: org.scalacheck.Arbitrary[A])org.scalacheck.Arbitrary[Item3[A]]scala> functor.laws[Item3].check
+ functor.invariantFunctor.identity: OK, passed 100 tests.
+ functor.invariantFunctor.composite: OK, passed 100 tests.
+ functor.identity: OK, passed 100 tests.
+ functor.composite: OK, passed 100 tests.

Item3的Functor实例是合理的。

实际上map就是(A => B) => (F[A] => F[B]),就是把(A => B)升格(lift)成(F[A] => F[B]):

case class Item3[A](i1: A, i2: A, i3: A)
implicit val item3Functor = new Functor[Item3] {def map[A,B](ia: Item3[A])(f: A => B): Item3[B] = Item3(f(ia.i1),f(ia.i2),f(ia.i3))
}                                                 //> item3Functor  : scalaz.Functor[scalaz.functor.Item3] = scalaz.functor$$anonf//| un$main$1$$anon$1@5e265ba4
val F = Functor[Item3]                            //> F  : scalaz.Functor[scalaz.functor.Item3] = scalaz.functor$$anonfun$main$1$$//| anon$1@5e265ba4
F.map(Item3("Morning","Noon","Night"))(_.length)  //> res0: scalaz.functor.Item3[Int] = Item3(7,4,5)
F.apply(Item3("Morning","Noon","Night"))(_.length)//> res1: scalaz.functor.Item3[Int] = Item3(7,4,5)
F(Item3("Morning","Noon","Night"))(_.length)      //> res2: scalaz.functor.Item3[Int] = Item3(7,4,5)
F.lift((s: String) => s.length)(Item3("Morning","Noon","Night"))//> res3: scalaz.functor.Item3[Int] = Item3(7,4,5)

虽然函数升格(function lifting (A => B) => (F[A] => F[B])是Functor的主要功能,但我们说过:一旦能够获取Item3类型的Functor实例我们就能免费使用所有的注入方法:

scalaz提供了Function1的Functor实例。Function1 Functor的map就是 andThen 也就是操作方调换的compose:

scala> (((_: Int) + 1) map((k: Int) => k * 3))(2)
res20: Int = 9scala> (((_: Int) + 1) map((_: Int) * 3))(2)
res21: Int = 9scala> (((_: Int) + 1) andThen ((_: Int) * 3))(2)
res22: Int = 9scala> (((_: Int) * 3) compose ((_: Int) + 1))(2)
res23: Int = 9

我们也可以对Functor进行compose:

scala> val f = Functor[List] compose Functor[Item3]
f: scalaz.Functor[[α]List[Item3[α]]] = scalaz.Functor$$anon$1@647ce8fdscala> val item3 = Item3("Morning","Noon","Night")
item3: Item3[String] = Item3(Morning,Noon,Night)scala> f.map(List(item3,item3))(_.length)
res25: List[Item3[Int]] = List(Item3(7,4,5), Item3(7,4,5))

反过来操作:

scala> val f1 = Functor[Item3] compose Functor[List]
f1: scalaz.Functor[[α]Item3[List[α]]] = scalaz.Functor$$anon$1@5b6a0166scala> f1.map(Item3(List("1"),List("22"),List("333")))(_.length)
res26: Item3[List[Int]] = Item3(List(1),List(2),List(3))

我们再试着在Item3类型上调用那些免费的注入方法:

scala> item3.fpair
res28: Item3[(String, String)] = Item3((Morning,Morning),(Noon,Noon),(Night,Night))scala> item3.strengthL(3)
res29: Item3[(Int, String)] = Item3((3,Morning),(3,Noon),(3,Night))scala> item3.strengthR(3)
res30: Item3[(String, Int)] = Item3((Morning,3),(Noon,3),(Night,3))scala> item3.fproduct(_.length)
res31: Item3[(String, Int)] = Item3((Morning,7),(Noon,4),(Night,5))scala> item3 as "Day"
res32: Item3[String] = Item3(Day,Day,Day)scala> item3 >| "Day"
res33: Item3[String] = Item3(Day,Day,Day)scala> item3.void
res34: Item3[Unit] = Item3((),(),())

我现在还没有想到这些函数的具体用处。不过从运算结果来看,用这些函数来产生一些数据模型用在游戏或者测试的模拟(simulation)倒是可能的。

scalaz提供了许多现成的Functor实例。我们先看看一些简单直接的实例:

scala> Functor[List].map(List(1,2,3))(_ + 3)
res35: List[Int] = List(4, 5, 6)scala> Functor[Option].map(Some(3))(_ + 3)
res36: Option[Int] = Some(6)scala> Functor[java.util.concurrent.Callable]
res37: scalaz.Functor[java.util.concurrent.Callable] = scalaz.std.java.util.concurrent.CallableInstances$$anon$1@4176ab89scala> Functor[Stream]
res38: scalaz.Functor[Stream] = scalaz.std.StreamInstances$$anon$1@4f5374b9scala> Functor[Vector]
res39: scalaz.Functor[Vector] = scalaz.std.IndexedSeqSubInstances$$anon$1@4367920a

对那些多个类型变量的类型我们可以采用部分施用方式:即type lambda来表示。一个典型的类型:Either[E,A],我们可以把Left[E]固定下来: Either[String, A],我们可以用type lambda来这样表述:

scala> Functor[({type l[x] = Either[String,x]})#l].map(Right(3))(_ + 3)
res41: scala.util.Either[String,Int] = Right(6)

如此这般我可以对Either类型进行map操作了。

函数类型的Functor是针对返回类型的:

scala> Functor[({type l[x] = String => x})#l].map((s: String) => s + "!")(_.length)("Hello")
res53: Int = 6scala> Functor[({type l[x] = (String,Int) => x})#l].map((s: String, i: Int) => s.length + i)(_ * 10)("Hello",5)
res54: Int = 100scala> Functor[({type l[x] = (String,Int,Boolean) => x})#l].map((s: String,i: Int, b: Boolean)=> s + i.toString + b.toString)(_.toUpperCase)("Hello",3,true)
res56: String = HELLO3TRUE


tuple类型的Functor是针对最后一个元素类型的:

scala> Functor[({type l[x] = (String,x)})#l].map(("a",1))(_ + 2)
res57: (String, Int) = (a,3)scala> Functor[({type l[x] = (String,Int,x)})#l].map(("a",1,"b"))(_.toUpperCase)
res58: (String, Int, String) = (a,1,B)scala> Functor[({type l[x] = (String,Int,Boolean,x)})#l].map(("a",1,true,Item3("a","b","c")))(i => i.map(_.toUpperCase))
res62: (String, Int, Boolean, Item3[String]) = (a,1,true,Item3(A,B,C))










这篇关于Scalaz(6)- typeclass:Functor-just map的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/887244

相关文章

Collection List Set Map的区别和联系

Collection List Set Map的区别和联系 这些都代表了Java中的集合,这里主要从其元素是否有序,是否可重复来进行区别记忆,以便恰当地使用,当然还存在同步方面的差异,见上一篇相关文章。 有序否 允许元素重复否 Collection 否 是 List 是 是 Set AbstractSet 否

Map

Map 是 Java 中用于存储键值对的集合接口。以下是对 Map 的详细介绍: 特点 键值对存储:每个元素包含一个键和一个值。 键唯一:键不能重复,但值可以重复。 无序/有序:根据具体实现,键值对的顺序可能无序(如 HashMap)或有序(如 TreeMap、LinkedHashMap)。 主要实现类 HashMap 基于哈希表,无序存储。 允许一个 null 键和多个 null 值。

Java中集合类Set、List和Map的区别

Java中的集合包括三大类,它们是Set、List和Map,它们都处于java.util包中,Set、List和Map都是接口,它们有各自的实现类。Set的实现类主要有HashSet和TreeSet,List的实现类主要有ArrayList,Map的实现类主要有HashMap和TreeMap。那么它们有什么区别呢? Set中的对象不按特定方式排序,并且没有重复对象。但它的有些实现类能对集合中的对

C++数据结构重要知识点(5)(哈希表、unordered_map和unordered_set封装)

1.哈希思想和哈希表 (1)哈希思想和哈希表的区别 哈希(散列、hash)是一种映射思想,本质上是值和值建立映射关系,key-value就使用了这种思想。哈希表(散列表,数据结构),主要功能是值和存储位置建立映射关系,它通过key-value模型中的key来定位数组的下标,将value存进该位置。 哈希思想和哈希表数据结构这两个概念要分清,哈希是哈希表的核心思想。 (2)unordered

【C++STL(十四)】一个哈希桶简单模拟实现unordered_map/set

目录 前言 一、改造哈希桶 改造结点类 改造主体  模板参数改造  迭代器(重点) 改造完整哈希桶 unordered_map模拟实现 unordered_set模拟实现 前言 前面的文章都有说unordered_map/set的底层结构就是哈希表,严格来说是哈希桶,那么接下来我们就尝试使用同一个哈希桶来模拟实现一下。整体的逻辑和一棵红黑树封装map/set类似,所以

Java中Map取值转String Null值处理

Map<String, Object> 直接取值转String String value = (String)map.get("key") 当map.get(“key”)为Null值时会报错。 使用String类的valueOf静态方法可以解决这个问题 String value = String.valueOf(map.get("key"))

Creating OpenAI Gym Environment from Map Data

题意:从地图数据创建 OpenAI Gym 环境 问题背景: I am just starting out with reinforcement learning and trying to create a custom environment with OpenAI gym. However, I am stumped with trying to create an enviro

【Java编程的逻辑】Map和Set

HashMap Map有键和值的概念。一个键映射到一个值,Map按照键存储和访问值,键不能重复。 HashMap实现了Map接口。 基本原理 HashMap的基本实现原理:内部有一个哈希表,即数组table,每个元素table[i]指向一个单向链表,根据键存取值,用键算出hash值,取模得到数组中的索引位置index,然后操作table[index]指向的单向链表。 存取的时候依据键的

RDD的map和flatMap

在 Apache Spark 中,map 和 flatMap 是 RDD(弹性分布式数据集)中最常用的转换操作之一。 map 假设你有一个包含整数的 RDD,你想要计算每个元素的平方。 from pyspark import SparkContextsc = SparkContext(appName="MapExample")# 创建一个包含整数的 RDDnumbers = sc.para

【python 多进程传参】pool.map() 函数传多参数

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。点这里可以跳转到教程。人工智能教程 一、背景介绍 相信很多人都用过,pool.map()函数,这个函数,有两个参数可以传,第一个参数传的是函数,第二个参数传的是数据列表。 那么怎么在第二个数据列表,多传几个参数呢,方法是通过对有多个参数的方法进行封装