【问题标题】:Haskell Pattern Match VectorsHaskell 模式匹配向量
【发布时间】:2017-08-10 23:20:14
【问题描述】:

我正在关注一个在线tutorial on Haskell。我们定义一个函数来添加二维向量,由数字的元组对表示。以下是显式类型声明,确保两个输入都是二维向量。

addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)

我理解为什么以下函数定义使用模式匹配:它描述了输入数据应符合的模式。

addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)  

为什么下面的替代函数定义不使用模式匹配? (fst) 和 (snd) 保证可以工作,因为输入被明确声明为长度为 2 的元组。

这两个函数定义有什么区别?

addVectors a b = (fst a + fst b, snd a + snd b)

【问题讨论】:

  • 嗯,这只是定义同一事物的不同风格。你的问题到底是什么?
  • 作为一般建议,我建议尽可能多地学习使用模式匹配,至少在初学者级别。 fst,snd 的替代方案是可以的,但是在这里我看到太多的初学者使用像 head,tail,fromJust 这样的危险函数,当模式匹配更安全时,这通常会导致崩溃,尤其是当使用 @ 打开警告时987654327@(强烈推荐)。

标签: haskell vector pattern-matching


【解决方案1】:

它们的严格程度不同。假设我们重命名它们:

> let addVectorsStrict (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
> let addVectorsLazy a b = (fst a + fst b, snd a + snd b)

addVectorsStrict undefined undefined 是 undefined——只要需要结果的外部 (,) 构造函数,就会执行模式匹配:

> case addVectorsStrict (error "A") (error "B") of (_, _) -> ()
*** Exception: A

但是addVectorsLazy undefined undefined 是(undefined, undefined)——模式匹配被推迟到需要结果的元素之一。

> case addVectorsLazy (error "A") (error "B") of (_, _) -> ()
()

基本上,addVectorsLazy 总是返回一个元组,其中的元素可能未计算。 addVectorsStrict 可能不会返回。您还可以使用惰性模式匹配获得addVectorsLazy 的效果:

> let addVectorsAlsoLazy ~(x1, y1) ~(x2, y2) = (x1 + x2, y1 + y2)
> case addVectorsAlsoLazy (error "A") (error "B") of (_, _) -> ()
()

为了更好地理解评估顺序,您可以使用Debug.Trace.trace 观察它:

addVectors
  (trace "first tuple evaluated"
    (trace "x1 evaluated" 1, trace "y1 evaluated" 2))
  (trace "second tuple evaluated"
    (trace "x2 evaluated" 3, trace "y2 evaluated" 4))

关于 Haskell 中求值的基本需要记住的是,它是由使用 case 和函数方程(脱糖为 case)的模式匹配驱动的。

在这种情况下无关紧要,但您可以懒惰地编写函数以避免在不需要计算结果的情况下评估昂贵的计算,或者如果您知道某些结果总是会严格地避免 thunk 的开销 需要。

一般来说,最好让你的数据结构字段变得严格,除非你需要它们是惰性的,而让你的函数是惰性的,除非你需要它们要严格。在这里,您可以创建一个严格的对类型来表示您的向量:

data Vector a = Vector !a !a

【讨论】:

  • 这是真的,但可能太微妙了,对 OP 或任何从 Google 提出这个问题的人来说都没有用。
  • 感谢您理解这个问题 - 因为我不了解 Haskell,所以我没有很好地表达它!也许我应该关注official tutorial。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 2019-03-01
相关资源
最近更新 更多