# Scalaz（30）－ Free ：Natural Tranformation ~> - map higher kinded types for free

当我们需要定义一些对应高阶类型进行相互类型转换的操作函数时，我们发现scala语言并不提供能定义这种函数的支持。举例来说：如果我们希望定义一个函数把对于任何T值的Option[T]转换成List[T]的话，我们可能这样定义：

```1 def toList[T](opt: Option[T]): List[T] = opt.toList
2                                                   //> toList: [T](opt: Option[T])List[T]
3 val hOptFun = toList _                            //> hOptFun  : Option[Nothing] => List[Nothing] = <function1>```

```1 hOptFun(None)                                     //> res0: List[Nothing] = List()
2 //hOptFun(Some(10)) //type mismatch;  found   : Int(10)  required: Nothing
3 //hOptFun(Some("hi")) //type mismatch;  found   : String("hi")   required: Nothing```

```/** A universally quantified function, usually written as `F ~> G`,
* for symmetry with `A => B`.
*
* Can be used to encode first-class functor transformations in the
* same way functions encode first-class concrete value morphisms;
* for example, `sequence` from [[scalaz.Traverse]] and `cosequence`
* from [[scalaz.Distributive]] give rise to `([a]T[A[a]]) ~>
* ([a]A[T[a]])`, for varying `A` and `T` constraints.
*/
trait NaturalTransformation[-F[_], +G[_]] {
self =>
def apply[A](fa: F[A]): G[A]
...```

```1 val optionToListTrans = new (Option ~> List) {
2   def apply[T](opt: Option[T]): List[T] = opt.toList
3 }                                                 //> optionToListTrans  : scalaz.~>[Option,List] = Exercises.naturaltransform\$\$an
4                                                   //| onfun\$main\$1\$\$anon\$1@2d554825
5 optionToListTrans(None)                           //> res1: List[Nothing] = List()
6 optionToListTrans(Some("hi"))                     //> res2: List[String] = List(hi)
7 optionToListTrans.apply(3.some)                   //> res3: List[Int] = List(3)```

0 条评论

## 相关文章

392

1113

32710

1674

### 用一个脚本学习 python

# -*- coding: utf-8 -*- # Python 2.7 学习参考脚本 # print 打印函数 print "Hello Worl...

2667

642

641

3418

### [Java 基础]基础语法

Java代码基本规范 大小写敏感：Java是大小写敏感的，这就意味着标识符Hello与hello是不同的。 类名：对于所有的类来说，类名的首字母应该大写。如果类...

1848

2674