我读了这个关于如何创建一个自定义的前奏库的博客文章。该库可以在这里找到。它做的一件事是禁止String
。它还定义了用于自动字符串转换的功能(此处)。我已OverloadedStrings
在cabal文件中启用。
在使用此库之前,我有:
data Point = Point Int Int
instance Show Point where
show (Point x y) = "(" ++ show x ++ ", " ++ show y ++ ")"
使用该库后,它show' is not a (visible) method of class
显示:“ Show'”
因此,我诉诸于创建一个自定义函数来显示数据类型:
showPoint :: Point -> LText
showPoint (Point x y) = toS ("(" ++ show x ++ ", " ++ show y ++ ")")
编译器说的用法toS, "(", show
是模棱两可的,但我不明白为什么。我是否必须要做一些类似此处建议的事情?
编辑:
必须禁用OverloadedStrings并将代码更改为以下内容:
showPoint :: Point -> LText
showPoint (Point x y) = toS "(" <> show x <> toS ", " <> show y <> toS ")"
想知道是否有可能在不禁用OverloadedStrings的情况下做同样的事情,所以我不必toS
每个都使用String
。
这对我有用:
{-# LANGUAGE OverloadedStrings #-}
module Test where
import Protolude
import qualified Base as PBase
data P = P Int
instance PBase.Show P where
show (P x) = "a P " ++ show x
更新
的protolude实现show
是常规功能(请参见Protolude.hs的结尾):
show :: (Show a, StringConv String b) => a -> b
show x = toS (PBase.show x)
因此,您需要一个PBase.Show
实例才能使用protolude的show函数。
另外protoludeshow
可以返回任何字符串类型,因此您不必通过定义PBase.show实例来强迫其他人使用String。
更新#2
您可以show
从导入以下类的typeclass函数GHC.Show
:
{-# LANGUAGE NoImplicitPrelude #-}
import Protolude
import GHC.Show
data P = P Int
instance Show P where
show (P x) = "<-- P " ++ GHC.Show.show x ++ " -->"
main = print (P 123)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句