gpt4 book ai didi

haskell - 记录的字段可以与某个值匹配并同时分配给一个参数吗?

转载 作者:行者123 更新时间:2023-12-03 10:41:07 25 4
gpt4 key购买 nike

在 Haskell wiki 上关于记录模式匹配的相对简短的文本之后,我不确定记录的字段是否可以与某个值匹配并同时分配给一个参数。

-- Sample record type
data Rec = Rec { uid :: Int, name :: String }

-- Function to update Rec's fields
updateRec :: Rec -> Rec

-- basic matching with record data constructor
updateRec (Rec _ []) = Rec 0 "Nobody"

-- dtto with as-pattern at 2nd param
updateRec (Rec idn ns@"Alice") = Rec (idn+1) (ns ++ "+1")

-- basic matching by fields values
updateRec Rec {name = "Bob", uid = 42} = Rec (10^6) "SuperBob"

-- Q: how to match by name field and assign it's value ?
updateRec Rec {name = "Bob", uid = idn} =
Rec {uid = (idn+1), name = ("Bob" ++ "+1")}

-- Q: as-pattern works only on the whole record, not on a field
updateRec rec@(Rec {name = "Bob", uid = idn}) =
Rec {uid = (idn+1), name = (name rec ++ "+1")}

-- Q: pattern guards do work, but they are a bit clumsy
updateRec Rec {name = uname, uid = idn}
| uname == "Bob" = Rec {uid = (idn+1), name = (uname ++ "+1")}
| otherwise = ...

那么是否有一些简洁的方法可以通过记录的字段进行模式匹配并同时分配其值?

备注 : 我想避免特定的 GHC 扩展。

最佳答案

字段名称本身就是模式,因此您可以使用另一个 as-pattern:

updateRec Rec {name = uname@"Bob", uid = idn@42} = ...

没有任何更简洁的方法可以做到这一点,标准或 GHC 扩展。当然,对于这样简单的情况,您可以简单地省略绑定(bind)并使用 "Bob"42直接在函数体中。

关于haskell - 记录的字段可以与某个值匹配并同时分配给一个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066026/

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