'@'在Haskell中意味着什么?

Rew*_*ert 8 haskell at-sign

我试过谷歌搜索但是做得很短.我通过阅读一些文章来进一步提高我的Haskell知识,并且我遇到了一个使用我以前从未见过的语法的文章.一个例子是:

reconstruct node@(Node a b c l r) parent@(Node b d le ri)
Run Code Online (Sandbox Code Playgroud)

我以前从未见过这些@.我试着在网上寻找答案但是很短暂.这只是一种嵌入标签以帮助使事情更清晰,或者它们对代码产生实际影响的方法吗?

Sib*_*ibi 17

它用于模式匹配.现在node变量将引用Node参数的整个数据类型Node a b c l r.因此,不是传递给函数Node a b c l r,而是可以使用node它来传递它.

一个更简单的例子来演示它:

data SomeType = Leaf Int Int Int | Nil deriving Show

someFunction :: SomeType -> SomeType
someFunction leaf@(Leaf _ _ _) = leaf
someFunction Nil = Leaf 0 0 0
Run Code Online (Sandbox Code Playgroud)

someFunction也可以写为:

someFunction :: SomeType -> SomeType
someFunction (Leaf x y z) = Leaf x y z
someFunction Nil = Leaf 0 0 0
Run Code Online (Sandbox Code Playgroud)

看第一个版本有多简单?

  • @AndrásKovács,但是它不需要对"Leaf {}"做一些解释吗? (2认同)

jpm*_*ier 6

除了@Sibi 的答案中描述的参数模式匹配用法之外,在 Haskell 中,“at”字符('@',也称为arobase字符)可以在某些上下文中用于强制输入决定。@Josh.F 在评论中提到了这一点。

不是默认语言功能的一部分,被称为Type Application Haskell 语言扩展。总之,扩展允许您为多态函数提供显式类型参数,例如read. 在经典的 .hs 源文件中,必须包含相关的编译指示:

{-#  LANGUAGE TypeApplications  #-}
Run Code Online (Sandbox Code Playgroud)

例子:

$ ghci
GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
 ?> 
 ?> let x = (read @Integer "33")

 <interactive>:4:10: error:
    Pattern syntax in expression context: read@Integer
    Did you mean to enable TypeApplications?
 ?> 
 ?> :set -XTypeApplications
 ?>
 ?> let x = (read @Integer "33")
 ?>
 ?> :t x
 x :: Integer
 ?> 
 ?> x
 33
 ?> 
Run Code Online (Sandbox Code Playgroud)