资讯专栏INFORMATION COLUMN

Scala类型推导

SQC / 1119人阅读

摘要:提供了类型推导来解决这个问题。函数式语言里比较经典的类型推导的方法是,并且它是在里首先使用的。的类型推导有一点点不同,不过思想上是一致的推导所有的约束条件,然后统一到一个类型上。而推导器是所有类型推导器的基础。

Scala类型推导

之剑

2016.5.1 00:38:12

类型系统 什么是静态类型?为什么它们很有用?

根据Picrce的说法:“类型系统是一个可以根据代码段计算出来的值对它们进行分类,然后通过语法的手段来自动检测程序错误的系统。”

类型可以让你表示函数的域和值域。例如,在数学里,我们经常看到下面的函数:

</>复制代码

  1. f: R -> N

这个定义告诉我们函数”f”的作用是把实数集里的数映射到自然集里。

抽象地说,这才是具体意义上的类型。类型系统给了我们一些表示这些集合的更强大的方式。

有了这些类型标识,编译器现在可以 静态地(在编译期)判断这个程序是正确的。

换句话说,如果一个值(在运行期)不能够满足程序里的限制条件的话,那么在编译期就会出错。

通常来说,类型检测器(typechecker)只能够保证不正确的的程序不能通过编译。但是,它不能够保证所有正确的程序都能通过编译。

由于类型系统的表达能力不断增加,使得我们能够生成出更加可靠的代码,因为它使得我们能够控制程序上的不可变,即是是程序还没有运行的情况下(在类型上限制bug的出现)。学术界一直在努力突破类型系统的表达能力的极限,包含值相关的类型。

注意,所有的类型信息都会在编译期擦除。后面不再需要。这个被称为类型擦除。比如,Java里面的泛型的实现.

Scala中的类型

Scala强大的类型系统让我们可以使用更具有表现力的表达式。一些主要的特点如下:

支持参数多态,泛型编程

支持(局部)类型推导,这就是你为什么不需要写val i: Int = 12: Int

支持存在向量(existential quantification),给一些没有名称的类型定义一些操作

支持视图。 给定的值从一个类型到其他类型的“可转换性”

参数多态

多态可以用来编写泛型代码(用于处理不同类型的值),并且不会减少静态类型的表达能力。

例如,没有参数多态的话,一个泛型的列表数据结构通常会是下面这样的写法(在Java还没有泛型的时候,确实是这样的):

</>复制代码

  1. scala> 2 :: 1 :: "bar" :: "foo" :: Nil
  2. res5: List[Any] = List(2, 1, bar, foo)

这样的话,我们就不能够恢复每个元素的类型信息。

</>复制代码

  1. scala> res5.head
  2. res6: Any = 2

这样一来,我们的应用里会包含一系列的类型转换(“asInstanceOf[]“),代码会缺少类型安全(因为他们都是动态类型的)。

多态是通过指定类型变量来达到的。

</>复制代码

  1. scala> def drop1[A](l: List[A]) = l.tail
  2. drop1: [A](l: List[A])List[A]
  3. scala> drop1(List(1,2,3))
  4. res1: List[Int] = List(2, 3)
多态是scala里的一等公民

简单来说,这意味着有一些你想在Scala里表达的类型概念会显得“太过于泛型”,从而导致编译器无法理解。所有的类型变量在运行期必须是确定的。

对于静态类型的一个比较常见的缺陷就是有太多的类型语法。Scala提供了类型推导来解决这个问题。

函数式语言里比较经典的类型推导的方法是 Hindlry-Milner,并且它是在ML里首先使用的。

Scala的类型推导有一点点不同,不过思想上是一致的:推导所有的约束条件,然后统一到一个类型上。

在Scala里,例如,你不能这样写:

</>复制代码

  1. scala> { x => x }
  2. :7: error: missing parameter type
  3. { x => x }

但是在OCaml里,你可以:

</>复制代码

  1. # fun x -> x;;
  2. - : "a -> "a =

在Scala里,所有的类型推导都是局部的。Scala一次只考虑一个表达式。例如:

</>复制代码

  1. scala> def id[T](x: T) = x
  2. id: [T](x: T)T
  3. scala> val x = id(322)
  4. x: Int = 322
  5. scala> val x = id("hey")
  6. x: java.lang.String = hey
  7. scala> val x = id(Array(1,2,3,4))
  8. x: Array[Int] = Array(1, 2, 3, 4)

在这里,类型都被隐藏了。Scala编译器自动推导参数的类型。注意我们也没有必要显示指定返回值的类型了。

型变

Scala的类型系统需要把类的继承关系和多态结合起来。类的继承使得类之间存在父子的关系。当把面向对象和多态结合在一起时,一个核心的问题就出来了:如果T"是T的子类,那么Container[T"]是不是Container[T]的子类呢?Variance注释允许你在类继承和多态类型之间表达下面的这些关系:

含义 Scala中的标记
covariant(协变) C[T’]是C[T]的子类 [+T]
contravariant(逆变) C[T]是C[T’]子类 [-T]
invariant(不变) C[T]和C[T’]不相关 [T]

子类关系的真正意思是:对于一个给定的类型T,如果T’是它的子类,那么T’可以代替T吗?

</>复制代码

  1. scala> class Contravariant[-A]
  2. defined class Contravariant
  3. scala> val cv: Contravariant[String] = new Contravariant[AnyRef]
  4. cv: Contravariant[AnyRef] = Contravariant@49fa7ba
  5. scala> val fail: Contravariant[AnyRef] = new Contravariant[String]
  6. :6: error: type mismatch;
  7. found : Contravariant[String]
  8. required: Contravariant[AnyRef]
  9. val fail: Contravariant[AnyRef] = new Contravariant[String]
量化(Quantification)

有时候你不需要给一个类型变量以名称,例如

</>复制代码

  1. scala> def count[A](l: List[A]) = l.size
  2. count: [A](List[A])Int

你可以用“通配符”来替代:

</>复制代码

  1. scala> def count(l: List[_]) = l.size
  2. count: (List[_])Int
什么是类型推导

先看个代码:

</>复制代码

  1. Map> m = new HashMap>();

是啊, 这简直太长了,我们不禁感叹,这编译器也太愚蠢了.几乎一半字符都是重复的!

针对泛型定义和实例太过繁琐的问题,在java 7 中引入了钻石运算符. 神奇的Coin项目,满足了你的心愿.

于是,你在java 7之后可以这样写了:

</>复制代码

  1. Map> m = new HashMap();

钻石运算符通常用于简化创建带有泛型对象的代码,可以避免运行时 的异常,并且它不再要求程序员在编码时显示书写冗余的类型参数。实际上,编译器在进行词法解析时会自动推导类型,自动为代码进行补全,并且编译的字节码与 以前无异。

当时在提案中,这个问题叫"Improved Type Inference for Generic Instance Creation",缩写ITIGIX听起来怪怪的,但是为啥叫钻石算法? 世界上, 哪有那么多为什么.

Scala正是因为做了类型推导, 让Coders感觉仿佛在写动态语言的代码.

在Scala中,高阶函数经常传递匿名函数.举个栗子:

一段定义泛型函数的代码

</>复制代码

  1. def dropWhile[A](list: List[A], f: A => Boolean): List[A]

当我们传入一个匿名函数f来调用它,

</>复制代码

  1. val mylist: List[Int] = List(1,2,3,4,5)
  2. val listDropped = dropWhile( mylist, (x: Int) => x < 4 )

listDropped的值是List(4,5)

我们用大脑可以轻易判断, 当list: List[A] 中的类型A在mylist声明的时候已经指定了Int, 那么很明显, 在第二个参数中,我们的x也必是Int.

很幸运Scala设计者们早已考虑到这一点,Scala编译器可以推导这种情况.但是你得按照Scala的规范限制来写你的dropWhile函数的签名(柯里化的): dropWhile( mylist )( f )

</>复制代码

  1. def dropWhile[A] ( list: List[A] ) ( f: A => Boolean ) : List[A] = list match {
  2. case Cons(h,t) if f(h) => dropWhile(t)(f)
  3. case _ => list
  4. }

如此而来,我们就可以直接像下面这样使用这个函数了:

</>复制代码

  1. val mylist: List[Int] = List(1,2,3,4,5)
  2. val droppedList = dropWhile( mylist ) ( x => x < 4 )

注意, x参数没有指定Int类型, 因为编译器直接通过mylist的泛型信息Int推导出x的类型也是Int.

类型推导是一门博大的学问,背后有繁冗的理论, 这在编译器设计开发的时候需要解决的问题.

Scala Haskell,ML
局部的(local)、基于流的(flow-based)类型推断 全局化的Hindley-Milner类型推断

在《Programming in Scala》一书中提到基于流的类型推断有它的局限性,但是对于面向对象的分支类型处理比Hindley-Mlner更加优雅。

基于流的类型推导在偏应用函数场景下,不能对参数类型省略

类型推导算法

类型推导(Type Inference)是现代高级语言中一个越来越常见的特性。其实,这个特性在函数式语言

中早有了广泛应用。而HindleyMilner推导器是所有类型推导器的基础。

Scala实现的一个简单的HindleyMilner推导器:

</>复制代码

  1. /*
  2. * http://dysphoria.net/code/hindley-milner/HindleyMilner.scala
  3. * Andrew Forrest
  4. *
  5. * Implementation of basic polymorphic type-checking for a simple language.
  6. * Based heavily on Nikita Borisov’s Perl implementation at
  7. * http://web.archive.org/web/20050420002559/www.cs.berkeley.edu/~nikitab/courses/cs263/hm.html
  8. * which in turn is based on the paper by Luca Cardelli at
  9. * http://lucacardelli.name/Papers/BasicTypechecking.pdf
  10. *
  11. * If you run it with "scala HindleyMilner.scala" it will attempt to report the types
  12. * for a few example expressions. (It uses UTF-8 for output, so you may need to set your
  13. * terminal accordingly.)
  14. *
  15. * Changes
  16. * June 30, 2011 by Liang Kun(liangkun(AT)baidu.com)
  17. * 1. Modify to enhance readability
  18. * 2. Extend to Support if expression in syntax
  19. *
  20. *
  21. *
  22. * Do with it what you will. :)
  23. */
  24. /** Syntax definition. This is a simple lambda calculous syntax.
  25. * Expression ::= Identifier
  26. * | Constant
  27. * | "if" Expression "then" Expression "else" Expression
  28. * | "lambda(" Identifier ") " Expression
  29. * | Expression "(" Expression ")"
  30. * | "let" Identifier "=" Expression "in" Expression
  31. * | "letrec" Identifier "=" Expression "in" Expression
  32. * | "(" Expression ")"
  33. * See the examples below in main function.
  34. */
  35. sealed abstract class Expression
  36. case class Identifier(name: String) extends Expression {
  37. override def toString = name
  38. }
  39. case class Constant(value: String) extends Expression {
  40. override def toString = value
  41. }
  42. case class If(condition: Expression, then: Expression, other: Expression) extends Expression {
  43. override def toString = "(if " + condition + " then " + then + " else " + other + ")"
  44. }
  45. case class Lambda(argument: Identifier, body: Expression) extends Expression {
  46. override def toString = "(lambda " + argument + "" + body + ")"
  47. }
  48. case class Apply(function: Expression, argument: Expression) extends Expression {
  49. override def toString = "(" + function + " " + argument + ")"
  50. }
  51. case class Let(binding: Identifier, definition: Expression, body: Expression) extends Expression {
  52. override def toString = "(let " + binding + " = " + definition + " in " + body + ")"
  53. }
  54. case class Letrec(binding: Identifier, definition: Expression, body: Expression) extends Expression {
  55. override def toString = "(letrec " + binding + " = " + definition + " in " + body + ")"
  56. }
  57. /** Exceptions may happened */
  58. class TypeError(msg: String) extends Exception(msg)
  59. class ParseError(msg: String) extends Exception(msg)
  60. /** Type inference system */
  61. object TypeSystem {
  62. type Env = Map[Identifier, Type]
  63. val EmptyEnv: Map[Identifier, Type] = Map.empty
  64. // type variable and type operator
  65. sealed abstract class Type
  66. case class Variable(id: Int) extends Type {
  67. var instance: Option[Type] = None
  68. lazy val name = nextUniqueName()
  69. override def toString = instance match {
  70. case Some(t) => t.toString
  71. case None => name
  72. }
  73. }
  74. case class Operator(name: String, args: Seq[Type]) extends Type {
  75. override def toString = {
  76. if (args.length == 0)
  77. name
  78. else if (args.length == 2)
  79. "[" + args(0) + " " + name + " " + args(1) + "]"
  80. else
  81. args.mkString(name + "[", ", ", "]")
  82. }
  83. }
  84. // builtin types, types can be extended by environment
  85. def Function(from: Type, to: Type) = Operator("→", Array(from, to))
  86. val Integer = Operator("Integer", Array[Type]())
  87. val Boolean = Operator("Boolean", Array[Type]())
  88. protected var _nextVariableName = "α";
  89. protected def nextUniqueName() = {
  90. val result = _nextVariableName
  91. _nextVariableName = (_nextVariableName.toInt + 1).toChar
  92. result.toString
  93. }
  94. protected var _nextVariableId = 0
  95. def newVariable(): Variable = {
  96. val result = _nextVariableId
  97. _nextVariableId += 1
  98. Variable(result)
  99. }
  100. // main entry point
  101. def analyze(expr: Expression, env: Env): Type = analyze(expr, env, Set.empty)
  102. def analyze(expr: Expression, env: Env, nongeneric: Set[Variable]): Type = expr match {
  103. case i: Identifier => getIdentifierType(i, env, nongeneric)
  104. case Constant(value) => getConstantType(value)
  105. case If(cond, then, other) => {
  106. val condType = analyze(cond, env, nongeneric)
  107. val thenType = analyze(then, env, nongeneric)
  108. val otherType = analyze(other, env, nongeneric)
  109. unify(condType, Boolean)
  110. unify(thenType, otherType)
  111. thenType
  112. }
  113. case Apply(func, arg) => {
  114. val funcType = analyze(func, env, nongeneric)
  115. val argType = analyze(arg, env, nongeneric)
  116. val resultType = newVariable()
  117. unify(Function(argType, resultType), funcType)
  118. resultType
  119. }
  120. case Lambda(arg, body) => {
  121. val argType = newVariable()
  122. val resultType = analyze(body,
  123. env + (arg -> argType),
  124. nongeneric + argType)
  125. Function(argType, resultType)
  126. }
  127. case Let(binding, definition, body) => {
  128. val definitionType = analyze(definition, env, nongeneric)
  129. val newEnv = env + (binding -> definitionType)
  130. analyze(body, newEnv, nongeneric)
  131. }
  132. case Letrec(binding, definition, body) => {
  133. val newType = newVariable()
  134. val newEnv = env + (binding -> newType)
  135. val definitionType = analyze(definition, newEnv, nongeneric + newType)
  136. unify(newType, definitionType)
  137. analyze(body, newEnv, nongeneric)
  138. }
  139. }
  140. protected def getIdentifierType(id: Identifier, env: Env, nongeneric: Set[Variable]): Type = {
  141. if (env.contains(id))
  142. fresh(env(id), nongeneric)
  143. else
  144. throw new ParseError("Undefined symbol: " + id)
  145. }
  146. protected def getConstantType(value: String): Type = {
  147. if(isIntegerLiteral(value))
  148. Integer
  149. else
  150. throw new ParseError("Undefined symbol: " + value)
  151. }
  152. protected def fresh(t: Type, nongeneric: Set[Variable]) = {
  153. import scala.collection.mutable
  154. val mappings = new mutable.HashMap[Variable, Variable]
  155. def freshrec(tp: Type): Type = {
  156. prune(tp) match {
  157. case v: Variable =>
  158. if (isgeneric(v, nongeneric))
  159. mappings.getOrElseUpdate(v, newVariable())
  160. else
  161. v
  162. case Operator(name, args) =>
  163. Operator(name, args.map(freshrec(_)))
  164. }
  165. }
  166. freshrec(t)
  167. }
  168. protected def unify(t1: Type, t2: Type) {
  169. val type1 = prune(t1)
  170. val type2 = prune(t2)
  171. (type1, type2) match {
  172. case (a: Variable, b) => if (a != b) {
  173. if (occursintype(a, b))
  174. throw new TypeError("Recursive unification")
  175. a.instance = Some(b)
  176. }
  177. case (a: Operator, b: Variable) => unify(b, a)
  178. case (a: Operator, b: Operator) => {
  179. if (a.name != b.name ||
  180. a.args.length != b.args.length) throw new TypeError("Type mismatch: " + a + " ≠ " + b)
  181. for(i <- 0 until a.args.length)
  182. unify(a.args(i), b.args(i))
  183. }
  184. }
  185. }
  186. // Returns the currently defining instance of t.
  187. // As a side effect, collapses the list of type instances.
  188. protected def prune(t: Type): Type = t match {
  189. case v: Variable if v.instance.isDefined => {
  190. val inst = prune(v.instance.get)
  191. v.instance = Some(inst)
  192. inst
  193. }
  194. case _ => t
  195. }
  196. // Note: must be called with v "pre-pruned"
  197. protected def isgeneric(v: Variable, nongeneric: Set[Variable]) = !(occursin(v, nongeneric))
  198. // Note: must be called with v "pre-pruned"
  199. protected def occursintype(v: Variable, type2: Type): Boolean = {
  200. prune(type2) match {
  201. case `v` => true
  202. case Operator(name, args) => occursin(v, args)
  203. case _ => false
  204. }
  205. }
  206. protected def occursin(t: Variable, list: Iterable[Type]) =
  207. list exists (t2 => occursintype(t, t2))
  208. protected val checkDigits = "^(d+)$".r
  209. protected def isIntegerLiteral(name: String) = checkDigits.findFirstIn(name).isDefined
  210. }
  211. /** Demo program */
  212. object HindleyMilner {
  213. def main(args: Array[String]){
  214. Console.setOut(new java.io.PrintStream(Console.out, true, "utf-8"))
  215. // extends the system with a new type[pair] and some builtin functions
  216. val left = TypeSystem.newVariable()
  217. val right = TypeSystem.newVariable()
  218. val pairType = TypeSystem.Operator("×", Array(left, right))
  219. val myenv: TypeSystem.Env = TypeSystem.EmptyEnv ++ Array(
  220. Identifier("pair") -> TypeSystem.Function(left, TypeSystem.Function(right, pairType)),
  221. Identifier("true") -> TypeSystem.Boolean,
  222. Identifier("false")-> TypeSystem.Boolean,
  223. Identifier("zero") -> TypeSystem.Function(TypeSystem.Integer, TypeSystem.Boolean),
  224. Identifier("pred") -> TypeSystem.Function(TypeSystem.Integer, TypeSystem.Integer),
  225. Identifier("times")-> TypeSystem.Function(TypeSystem.Integer,
  226. TypeSystem.Function(TypeSystem.Integer, TypeSystem.Integer))
  227. )
  228. // example expressions
  229. val pair = Apply(
  230. Apply(
  231. Identifier("pair"), Apply(Identifier("f"), Constant("4"))
  232. ),
  233. Apply(Identifier("f"), Identifier("true"))
  234. )
  235. val examples = Array[Expression](
  236. // factorial
  237. Letrec(Identifier("factorial"), // letrec factorial =
  238. Lambda(Identifier("n"), // lambda n =>
  239. If(
  240. Apply(Identifier("zero"), Identifier("n")),
  241. Constant("1"),
  242. Apply(
  243. Apply(Identifier("times"), Identifier("n")),
  244. Apply(
  245. Identifier("factorial"),
  246. Apply(Identifier("pred"), Identifier("n"))
  247. )
  248. )
  249. )
  250. ), // in
  251. Apply(Identifier("factorial"), Constant("5"))
  252. ),
  253. // Should fail:
  254. // fn x => (pair(x(3) (x(true))))
  255. Lambda(Identifier("x"),
  256. Apply(
  257. Apply(Identifier("pair"),
  258. Apply(Identifier("x"), Constant("3"))
  259. ),
  260. Apply(Identifier("x"), Identifier("true"))
  261. )
  262. ),
  263. // pair(f(3), f(true))
  264. Apply(
  265. Apply(Identifier("pair"), Apply(Identifier("f"), Constant("4"))),
  266. Apply(Identifier("f"), Identifier("true"))
  267. ),
  268. // letrec f = (fn x => x) in ((pair (f 4)) (f true))
  269. Let(Identifier("f"), Lambda(Identifier("x"), Identifier("x")), pair),
  270. // Should fail:
  271. // fn f => f f
  272. Lambda(Identifier("f"), Apply(Identifier("f"), Identifier("f"))),
  273. // let g = fn f => 5 in g g
  274. Let(
  275. Identifier("g"),
  276. Lambda(Identifier("f"), Constant("5")),
  277. Apply(Identifier("g"), Identifier("g"))
  278. ),
  279. // example that demonstrates generic and non-generic variables:
  280. // fn g => let f = fn x => g in pair (f 3, f true)
  281. Lambda(Identifier("g"),
  282. Let(Identifier("f"),
  283. Lambda(Identifier("x"), Identifier("g")),
  284. Apply(
  285. Apply(Identifier("pair"),
  286. Apply(Identifier("f"), Constant("3"))
  287. ),
  288. Apply(Identifier("f"), Identifier("true"))
  289. )
  290. )
  291. ),
  292. // Function composition
  293. // fn f (fn g (fn arg (f g arg)))
  294. Lambda( Identifier("f"),
  295. Lambda( Identifier("g"),
  296. Lambda( Identifier("arg"),
  297. Apply(Identifier("g"), Apply(Identifier("f"), Identifier("arg")))
  298. )
  299. )
  300. )
  301. )
  302. for(eg <- examples){
  303. tryexp(myenv, eg)
  304. }
  305. }
  306. def tryexp(env: TypeSystem.Env, expr: Expression) {
  307. try {
  308. val t = TypeSystem.analyze(expr, env)
  309. print(t)
  310. }catch{
  311. case t: ParseError => print(t.getMessage)
  312. case t: TypeError => print(t.getMessage)
  313. }
  314. println(":
  315. " + expr)
  316. }
  317. }
  318. HindleyMilner.main(argv)

Haskell写的一个 合一算法的简单实现:

https://github.com/yihuang/haskell-snippets/blob/master/Unif.hs

</>复制代码

  1. module Main where
  2. import Data.List (intersperse)
  3. import Control.Monad
  4. -- utils --
  5. mapFst :: (a -> b) -> (a, c) -> (b, c)
  6. mapFst f (a, c) = (f a, c)
  7. -- types --
  8. type Name = String
  9. data Term = Var Name
  10. | App Name [Term]
  11. -- 表示一个替换关系
  12. type Sub = (Term, Name)
  13. -- implementation --
  14. -- 检查变量 Name 是否出现在 Term 中
  15. occurs :: Name -> Term -> Bool
  16. occurs x t = case t of
  17. (Var y) -> x==y
  18. (App _ ts) -> and . map (occurs x) $ ts
  19. -- 使用 Sub 对 Term 进行替换
  20. sub :: Sub -> Term -> Term
  21. sub (t1, y) t@(Var a)
  22. | a==y = t1
  23. | otherwise = t
  24. sub s (App f ts) = App f $ map (sub s) ts
  25. -- 使用 Sub 列表对 Term 进行替换
  26. subs :: [Sub] -> Term -> Term
  27. subs ss t = foldl (flip sub) t ss
  28. -- 把两个替换列表组合起来,同时用新加入的替换对其中所有 Term 进行替换
  29. compose :: [Sub] -> [Sub] -> [Sub]
  30. compose [] s1 = s1
  31. compose (s:ss) s1 = compose ss $ s : iter s s1
  32. where
  33. iter :: Sub -> [Sub] -> [Sub]
  34. iter s ss = map (mapFst (sub s)) ss
  35. -- 合一函数
  36. unify :: Term -> Term -> Maybe [Sub]
  37. unify t1 t2 = case (t1, t2) of
  38. (Var x, Var y) -> if x==y then Just [] else Just [(t1, y)]
  39. (Var x, App _ _) -> if occurs x t2 then Nothing else Just [(t2, x)]
  40. (App _ _, Var x) -> if occurs x t1 then Nothing else Just [(t1, x)]
  41. (App n1 ts1, App n2 ts2)
  42. -> if n1/=n2 then Nothing else unify_args ts1 ts2
  43. where
  44. unify_args [] [] = Just []
  45. unify_args _ [] = Nothing
  46. unify_args [] _ = Nothing
  47. unify_args (t1:ts1) (t2:ts2) = do
  48. u <- unify t1 t2
  49. let update = map (subs u)
  50. u1 <- unify_args (update ts1) (update ts2)
  51. return (u1 `compose` u)
  52. -- display --
  53. instance Show Term where
  54. show (Var s) = s
  55. show (App name ts) = name++"("++(concat . intersperse "," $ (map show ts))++")"
  56. showSub (t, s) = s ++ " -> " ++ show t
  57. -- test cases --
  58. a = Var "a"
  59. b = Var "b"
  60. c = Var "c"
  61. d = Var "d"
  62. x = Var "x"
  63. y = Var "y"
  64. z = Var "z"
  65. f = App "f"
  66. g = App "g"
  67. j = App "j"
  68. test t1 t2 = do
  69. putStrLn $ show t1 ++ " <==> " ++ show t2
  70. case unify t1 t2 of
  71. Nothing -> putStrLn "unify fail"
  72. Just u -> putStrLn $ concat . intersperse "
  73. " $ map showSub u
  74. testcases = [(j [x,y,z],
  75. j [f [y,y], f [z,z], f [a,a]])
  76. ,(x,
  77. f [x])
  78. ,(f [x],
  79. y)
  80. ,(f [a, f [b, c], g [b, a, c]],
  81. f [a, a, x])
  82. ,(f [d, d, x],
  83. f [a, f [b, c], f [b, a, c]])
  84. ]
  85. main = forM testcases (uncurry test)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65871.html

相关文章

  • 函数范式入门(什么是函数式编程)

    摘要:第一节函数式范式什么是函数式编程函数式编程英语或称函数程序设计,又称泛函编程,是一种编程范型,它将电脑运算视为数学上的函数计算,并且避免使用程序状态以及易变对象。 第一节 函数式范式 1. 什么是函数式编程 函数式编程(英语:functional programming)或称函数程序设计,又称泛函编程,是一种编程范型,它将电脑运算视为数学上的函数计算,并且避免使用程序状态以及易变对...

    StonePanda 评论0 收藏0
  • 函数范式入门(惰性求值与函数式状态)

    摘要:纯函数式状态随机数生成器很明显,原有的函数不是引用透明的,这意味着它难以被测试组合并行化。售货机在输出糖果时忽略所有输入本章知识点惰性求值函数式状态 第二节 惰性求值与函数式状态 在下面的代码中我们对List数据进行了一些处理 List(1,2,3,4).map(_ + 10).filter(_ % 2 == 0).map(_ * 3) 考虑一下这段程序是如何求值的,如果我们跟踪一下...

    Jrain 评论0 收藏0
  • Akka系列(五):Java和Scala中的Future

    摘要:随着的核数的增加,异步编程模型在并发领域中的得到了越来越多的应用,由于是一门函数式语言,天然的支持异步编程模型,今天主要来看一下和中的,带你走入异步编程的大门。 随着CPU的核数的增加,异步编程模型在并发领域中的得到了越来越多的应用,由于Scala是一门函数式语言,天然的支持异步编程模型,今天主要来看一下Java和Scala中的Futrue,带你走入异步编程的大门。 Future 很多...

    YJNldm 评论0 收藏0
  • 函数式编程与面向对象编程[1]: Lambda表达式 函数柯里化 高阶函数

    摘要:函数式编程与面向对象编程表达式函数柯里化高阶函数之剑什么是表达式例子定义表达式是一个匿名函数,表达式基于数学中的演算得名,直接对应于其中的抽象,是一个匿名函数,即没有函数名的函数。 函数式编程与面向对象编程[1]: Lambda表达式 函数柯里化 高阶函数.md 之剑 2016.5.2 11:19:09 什么是lambda表达式 例子 For example, in Lisp the...

    张金宝 评论0 收藏0

发表评论

0条评论

SQC

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<