gpt4 book ai didi

haskell - 如何阅读haskell中的语法 `Typ{..}`?

转载 作者:行者123 更新时间:2023-12-04 03:00:25 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





pattern matching of the form: Option{..} <-

(1 个回答)


4年前关闭。




阅读图书馆代码时here我注意到一个看起来很奇怪的语法,我无法理解:

momenta
:: (KnownNat m, KnownNat n)
=> System m n
-> Config n
-> R n
momenta Sys{..} Cfg{..} = tr j #> diag _sysInertia #> j #> cfgVelocities
-- ^^^^^^^^^^^^^^^ the syntax in question
where
j = _sysJacobian cfgPositions
System的相关定义包括一条记录 { _sysJacobian :: R n -> L m n } , 和 { cfgVelocities :: R n }Config 的记录声明的一部分所以我相信我知道代码的作用,我认为代码的可读性很强,对作者的支持。

问题是:这种语法叫什么,我该如何使用它?

最佳答案

总之 : 它是 GHC 的扩展调用 RecordWildCards .

在 Haskell 中,您可以使用 record syntax定义数据类型。例如:

data Foo = Bar { foo :: Int, bar :: String } | Qux { foo :: Int, qux :: Int }

然后,我们可以在数据构造函数上进行模式匹配,并匹配零个或多个参数,例如:
someFunction :: Int -> Foo -> Foo
someFunction dd (Bar {foo=x}) = dd + x
someFunction dd (Qux {foo=x, qux=y}) = dd + x + y

但是可能会发生我们需要访问大量(甚至全部)参数的情况。例如:
someOtherFunction :: Foo -> Int
someOtherFunction (Bar {foo=foo, bar=bar}) = foo
someOtherFunction (Qux {foo=foo, qux=qux}) = foo + qux

如果参数的数量相当大,那么这变得很麻烦。有一个扩展 RecordWildCards :
{-# LANGUAGE RecordWildCards #-}

这将为每个参数隐式写入 foo , foo=foo如果你写 {..}当我们记录模式匹配时。

所以我们可以这样写:
someOtherFunction :: Foo -> Int
someOtherFunction (Bar {..}) = foo
someOtherFunction (Qux {..}) = foo + qux

所以这里编译器隐式地将所有参数与同名变量进行模式匹配,这样我们就可以在没有显式模式匹配的情况下访问这些参数,也不需要使用 getter。

因此,优点是我们在必须手动编写的大代码块上节省了很多。然而,缺点是参数不再显式,因此代码更难理解。我们看到实际存在 getter 对应物的参数的使用,因此它可能会引入一些混淆。

就像@leftroundabout 所说,可能是 lenses也可以做到这一点,它将防止引入基本上影响 setter/getter 的变量等。

也可以合并 RecordWildCards对参数进行模式匹配,例如:
someOtherFunction :: Foo -> Int
someOtherFunction (Bar {bar=[], ..}) = foo
someOtherFunction (Bar {..}) = foo + 42
someOtherFunction (Qux {..}) = foo + qux

所以在这里以防万一 bar Foo 的参数带有 Bar 的实例数据构造函数是空字符串,我们返回 foo值,否则我们添加 42给它。

关于haskell - 如何阅读haskell中的语法 `Typ{..}`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50268795/

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