gpt4 book ai didi

function - 为什么在函数定义中首选模式匹配?

转载 作者:行者123 更新时间:2023-12-04 13:58:39 26 4
gpt4 key购买 nike

我正在阅读来自 learnyouahaskell 的“learnyouahaskell”教程.那里写着:

Pattern matching can also be used on tuples. What if we wanted to make a function that takes two vectors in a 2D space (that are in the form of pairs) and adds them together? To add together two vectors, we add their x components separately and then their y components separately. Here's how we would have done it if we didn't know about pattern matching:

addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)  
addVectors a b = (fst a + fst b, snd a + snd b)

Well, that works, but there's a better way to do it. Let's modify the function so that it uses pattern matching.

addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)  
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

There we go! Much better. Note that this is already a catch-all pattern. The type of addVectors (in both cases) is addVectors :: (Num a) => (a, a) -> (a, a) - > (a, a), so we are guaranteed to get two pairs as parameters.



我的问题是:如果两个定义产生相同的签名,为什么模式匹配是首选方式?

最佳答案

我认为在这种情况下,模式匹配更直接地表达了你的意思。

在功能应用案例中,需要知道什么fstsnd做,并从中推断出ab是添加元素的元组。

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

我们有 snd 的事实和 fst分解元组的函数在这里分散注意力。

在模式匹配的情况下,输入是什么(一个元组,我们称之为 x1y1 和一个元组......等)以及它是如何被解构的。并且它也立即清楚发生了什么,它们的元素是如何添加的。
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

这几乎就像数学定义:

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



直截了当,没有分心:-)

你可以从字面上用 Haskell 写这个:
(x₁, y₁) `addVector` (x₂, y₂) = (x₁ + x₂, y₁ + y₂)

关于function - 为什么在函数定义中首选模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com