gpt4 book ai didi

haskell - 如何在实现 `instance`时隐藏辅助函数

转载 作者:行者123 更新时间:2023-12-02 14:16:08 25 4
gpt4 key购买 nike

我有data RegEx并且我想实现instance Show a => Show RegEx a。这是我的代码:

showAtom :: Show a => RegEx a -> String
showAtom (Lit x) = show x
showAtom r = "(" ++ (show r) ++ ")"

instance Show a => Show (RegEx a) where
show (Lit x) = show [x]
show (Opt r) = (showAtom r) ++ "?"
show (Alt p q) = (showAtom p) ++ "|" ++ (showAtom q)
show (Seq p q) = (show p) ++ (show q)
show (Rep r) = (showAtom r) ++ "*"

showAtom 函数只是一个实现细节。有什么方法可以隐藏它,使其仅在 instance 定义中可见吗?或者更好的是,使其仅在 show 中可见。

最佳答案

这样的事情应该有效:

instance Show a => Show (RegEx a) where
show x = show' x
where
showAtom :: Show a => RegEx a -> String
showAtom (Lit x) = show x
showAtom r = "(" ++ (show r) ++ ")"

show' (Lit x) = show [x]
show' (Opt r) = (showAtom r) ++ "?"
show' (Alt p q) = (showAtom p) ++ "|" ++ (showAtom q)
show' (Seq p q) = (show p) ++ (show q)
show' (Rep r) = (showAtom r) ++ "*"

或者,您可以从模块的导出列表中排除 showAtom

关于haskell - 如何在实现 `instance`时隐藏辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256880/

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