gpt4 book ai didi

haskell - 在 Haskell 案例语句中省略构造函数参数

转载 作者:行者123 更新时间:2023-12-01 09:26:33 25 4
gpt4 key购买 nike

省略函数参数是简洁 Haskell 代码的好工具。

h :: String -> Int
h = (4 +) . length

如果在 case 语句中省略数据构造函数参数会怎样。下面的代码可能被认为有点邋遢,其中 siAB 中的最终参数但在每个案例匹配的正文中作为最终参数重复。

f :: Foo -> Int
f = \case
A s -> 4 + length s
B i -> 2 + id i

有没有办法在模式匹配中省略这些参数?对于具有大量参数的构造函数,这将从根本上缩短代码宽度。例如。以下伪代码。

g :: Foo -> Int
g = \case
{- match `A` constructor -> function application to A's arguments -}
A -> (4 +) . length
{- match `B` constructor -> function application to B's arguments -}
B -> (2 +) . id

最佳答案

GHC 扩展 RecordWildCards 让您可以简洁地将构造函数的所有字段纳入范围(当然,这需要您为这些字段命名)。

{-# LANGUAGE LambdaCase, RecordWildCards #-}

data Foo = Foo {field1, field2 :: Int} | Bar {field1 :: Int}

baz = \case
Foo{..} -> 4 + field2
Bar{..} -> 2 + field1

-- plus it also "sucks in" fields from a scope
mkBar400 = let field1 = 400 in Bar{..}

`

关于haskell - 在 Haskell 案例语句中省略构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22537840/

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