如何重写显示一个新类型? [英] How does one override show for a newtype?
问题描述
我想重写Haskell中的默认整数构造函数,以便它们生成字符串(主要是为了好奇,但暂时为LaTeX的\ frac {} {}带来不便)。
我希望能够使用语言本身,而不是特殊的解析器,但我想这可能不会奏效......
< pre $
$ b $ new
$ b $ )
default(A)
(+):: A - > (A→String)
(A a)+(A b)=(显示a)+++++(显示b)
main2 = 3 + 4
main :: IO()
main = putStrLn main2
上面的问题是,+函数只适用于(A,A)而不是(A,String)等。如果仅仅忽略了模式匹配(A a)而不是写入a,那么show()函数预先设置A,所以3变成A 3而不是3。
我想重写Show for A,但它似乎很头疼......
code> A >的实例,那么就不要派生它并创建自己的实例:$ pre >
newtype A =一个Int派生(Eq,Num)
实例显示A
显示(A a)=显示
$ c
$ b 然后你可以这样写:
(+)::(Show a,Show b)=> a - > b - >字符串
a + b =显示a +++++显示b
当然,如果你正在定义你自己的 +
运算符,那么我认为你的问题不需要 newtype A
声明:
模块Main其中
导入前奏隐藏((+))
(+)::(Show a,Show b)=> a - > b - >字符串
a + b =显示a +++++显示b
aSum = 3 + 4
main :: IO()
main = putStrLn aSum
I want to override the default integer constructors in Haskell so they produce strings (mostly for curiosity, but temporarily to make a nice input alternative for LaTeX's \frac{}{} inconvenience).
I wanted to be able to use the language itself, instead of a special parser, but I guess that's probably not going to work out...
module Main where
import Prelude hiding ((+))
newtype A = A Int deriving (Eq, Show, Num)
default (A)
(+) :: A -> (A -> String)
(A a) + (A b) = (show a) ++ " + " ++ (show b)
main2 = 3+4
main :: IO ()
main = putStrLn main2
The problem with the above is that the + function only works for (A, A) instead of (A, String), etc. If one simply leaves out the pattern match "(A a)" and writes "a" instead, then the show() function prepends "A " so "3" becomes "A 3" instead of just "3".
I want to override Show for A, but it seems to be quite a headache...
解决方案 If you want your own Show
instance for A
, then just don't derive it and make your own instance:
newtype A = A Int deriving (Eq, Num)
instance Show A where
show (A a) = show a
Then you can write something like:
(+) :: (Show a, Show b) => a -> b -> String
a + b = show a ++ " + " ++ show b
Of course, if you are defining your own +
operator like that, then I don't think your problem requires the newtype A
declaration:
module Main where
import Prelude hiding ((+))
(+) :: (Show a, Show b) => a -> b -> String
a + b = show a ++ " + " ++ show b
aSum = 3 + 4
main :: IO ()
main = putStrLn aSum
这篇关于如何重写显示一个新类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!