gpt4 book ai didi

Haskell 私有(private)记录,如 OCaml

转载 作者:行者123 更新时间:2023-12-04 22:54:49 25 4
gpt4 key购买 nike

在 OCaml 模块签名中,我可以写:

type monotype = private {
monotype_free_variables: StringSet.t Lazy.t;
monotype_description: monotype_description;
}

(注意 private 的使用。)

这允许导入我的模块的代码与 monotype_description 等字段进行模式匹配但不允许代码导入我的模块来构造记录。

我可以在 Haskell 中编写具有类似访问权限的代码吗?我想对 monotypeDescription 进行模式匹配字段不允许记录构造。

我知道 PatternSynonyms语言扩展存在,但我不知道如何使用它。如果可以的话,我也更喜欢更简单的解决方案。

最佳答案

如果不至少允许记录更新(您要么导入字段),就无法匹配字段。我认为限制更多,因为没有明显的语法用于仅导入访问器......

正确的解决方案是真正使用 PatternSynonyms .您需要一个单向模式:

{-# LANGUAGE PatternSynonyms #-}
module MyModule ( Monotype(Monotype) ) where

import Data.Set

data Monotype = MT (Set String) String

pattern Monotype :: Set String -> String -> Monotype
pattern Monotype { monotype_free_variables, monotype_description }
<- MT monotype_free_variables monotype_description

现在,您可以匹配 Monotype { monotype_free_variables, monotype_description }但你不能构造它:
λ> Monotype { monotype_free_variables = f1, monotype_description = f2 } = m1
λ> Monotype f1 f2 = m1
λ> m3 = Monotype { monotype_free_variables = mempty, monotype_description = "" }
<interactive>:3:6: error:
• non-bidirectional pattern synonym ‘Monotype’ used in an expression
• In the expression:
Monotype
{monotype_free_variables = mempty, monotype_description = ""}
In an equation for ‘m3’:
m3
= Monotype
{monotype_free_variables = mempty, monotype_description = ""}
λ> m3 = Monotype mempty ""

<interactive>:4:6: error:
• non-bidirectional pattern synonym ‘Monotype’ used in an expression
• In the expression: Monotype mempty ""
In an equation for ‘m3’: m3 = Monotype mempty ""

关于Haskell 私有(private)记录,如 OCaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413440/

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