创建一个可以同时包含int和字符串的类型 [英] Create a type that can contain an int and a string in either order
问题描述
我正在关注 Haskell简介,对于这个特殊的地方(用户定义的类型2.2),我感到特别晦涩.到目前为止,我什至都不了解代码的哪一部分,以及作者的想法.(什么是 Pt
-从来没有在任何地方定义它?).不用说,我无法执行/编译.
I'm following this introduction to Haskell, and this particular place (user defined types 2.2) I'm finding particularly obscure. To the point, I don't even understand what part of it is code, and what part is the thoughts of the author. (What is Pt
- it is never defined anywhere?). Needless to say, I can't execute / compile it.
作为一个使我更容易理解的示例,我想定义一个类型,它是一对整数和一个字符串,或者一对字符串和一个整数,但没有别的.
As an example that would make it easier for me to understand, I wanted to define a type, which is a pair of an Integer and a String, or a String and an Integer, but nothing else.
将使用它的理论函数如下所示:
The theoretical function that would use it would look like so:
combine :: StringIntPair -> String
combine a b = (show a) ++ b
combine a b = a ++ (show b)
如果您需要有效的代码,也可以执行相同的操作,下面是执行此操作的CL代码:
If you need a working code, that does the same, here's CL code for doing it:
(defgeneric combine (a b)
(:documentation "Combines strings and integers"))
(defmethod combine ((a string) (b integer))
(concatenate 'string a (write-to-string b)))
(defmethod combine ((a integer) (b string))
(concatenate 'string (write-to-string a) b))
(combine 100 "500")
推荐答案
这是定义数据类型的一种方法:
Here's one way to define the datatype:
data StringIntPair = StringInt String Int |
IntString Int String
deriving (Show, Eq, Ord)
请注意,我已经为类型 StringIntPair
定义了两个构造函数,它们分别是 StringInt
和 IntString
.
Note that I've defined two constructors for type StringIntPair
, and they are StringInt
and IntString
.
现在定义 combine
:
combine :: StringIntPair -> String
combine (StringInt s i) = s ++ (show i)
combine (IntString i s) = (show i) ++ s
我正在使用模式匹配来匹配构造函数并选择正确的行为.
I'm using pattern matching to match the constructors and select the correct behavior.
以下是一些用法示例:
*Main> let y = StringInt "abc" 123
*Main> let z = IntString 789 "a string"
*Main> combine y
"abc123"
*Main> combine z
"789a string"
*Main> :t y
y :: StringIntPair
*Main> :t z
z :: StringIntPair
有关示例的一些注意事项:
A few things to note about the examples:
-
StringIntPair
是类型;在解释器中执行:t< expression>
会显示表达式的类型 -
StringInt
和IntString
是相同类型的构造函数 - 竖线(
|
)分隔构造函数 - 一个编写良好的函数应该匹配其参数类型的每个构造函数;这就是为什么我用两种模式编写
combine
的原因,每个构造函数一个模式
StringIntPair
is a type; doing:t <expression>
in the interpreter shows the type of an expressionStringInt
andIntString
are constructors of the same type- the vertical bar (
|
) separates constructors - a well-written function should match each constructor of its argument's types; that's why I've written
combine
with two patterns, one for each constructor
这篇关于创建一个可以同时包含int和字符串的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!