在Haskell处理`show`

Chi*_*ffa 1 haskell

我有一个功能ip,我无法改变:

ip = show a ++ show b ++ show c ++ show d
Run Code Online (Sandbox Code Playgroud)

我必须定义a,b,cd因此:

GHCi> ip
"127.224.120.12"
Run Code Online (Sandbox Code Playgroud)

成立.我怎么做?

chi*_*chi 10

使用浮点数:

> let ip a b c d = show a ++ show b ++ show c ++ show d
> ip 127.2 24.12 0.1 2
"127.224.120.12"
Run Code Online (Sandbox Code Playgroud)

  • @dfeuer我猜这个问题的"难题"方面只有Haskellers才能理解,因为它取决于如何定义`show`.非haskellers可能会猜测`String`上的`show = id`,因为例如`someString.toString()`与某些OOP语言中的`someString`相同.如果是这样的话,解决这个问题就没有任何挑战.如果CodeGolfers只是认为这是一个常规的一般编程问题,我并不感到惊讶. (2认同)

Sam*_*den 5

您可以通过不同的方式执行此操作。无论如何,默认Show实例可能不适合您,这是问题的核心:您将要使用自定义Show实例定义自己的类型。使用自定义实例(或隐藏实例)重新定义类型的常用方法是使用newtype

我们可以使用Show具有String-like类型的其他实例,这样就不会转义或添加"

newtype MyStr = MyStr String

instance Show MyStr where
  show (MyStr s) = s

ip a b c d = show a ++ show b ++ show c ++ show d

a = MyStr "127."
b = MyStr "224."
c = MyStr "120."
d = MyStr "12"

main = print $ ip a b c d
Run Code Online (Sandbox Code Playgroud)

另一种可能性是在使用时为附加Inta 的类型定义替代.方法show。然后,我们使用这种类型的前三个参数ip,并使用常用Int的最后一个参数(abc并且d可以有不同的类型)。

newtype MyInt = MyInt Int

instance Show MyInt where
  show (MyInt s) = show s ++ "."

ip a b c d = show a ++ show b ++ show c ++ show d

a = MyInt 127
b = MyInt 224
c = MyInt 120
d = 12

main = print $ ip a b c d
Run Code Online (Sandbox Code Playgroud)

请注意,在这两种情况下,解决方案都有些困难,但这是由于问题的性质所致。通常,您通常希望的实例Show本质上是技术性的而不是“风格”的:您希望显示有关值的所有信息,最好以一种可读取的方式read(通过定义相应的Read实例)显示。对于样式输出,漂亮的打印机更适合。