创建一个可以按任意顺序包含int和字符串的类型

4 haskell types

我正在关注Haskell的介绍,这个特殊的地方(用户定义的类型2.2)我发现它特别模糊.到目前为止,我甚至不了解代码的哪一部分,以及作者的思想是什么部分.(什么是Pt- 它永远不会在任何地方定义?).不用说,我无法执行/编译它.

作为一个让我更容易理解的例子,我想要定义一个类型,它是一对Integer和String,或者一个String和一个Integer,但没有别的.

使用它的理论函数看起来如下:

combine :: StringIntPair -> String
combine a b = (show a) ++ b
combine a b = a ++ (show b)
Run Code Online (Sandbox Code Playgroud)

如果你需要一个有效的代码,那么这里有CL代码:

(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")
Run Code Online (Sandbox Code Playgroud)

Mat*_*ick 8

这是定义数据类型的一种方法:

data StringIntPair = StringInt String Int | 
                     IntString Int String 
    deriving (Show, Eq, Ord)
Run Code Online (Sandbox Code Playgroud)

请注意,我为类型定义了两个构造函数StringIntPair,它们是StringIntIntString.

现在在定义中combine:

combine :: StringIntPair -> String
combine (StringInt s i) = s ++ (show i)
combine (IntString i s) = (show i) ++ s
Run Code Online (Sandbox Code Playgroud)

我正在使用模式匹配来匹配构造函数并选择正确的行为.

以下是一些用法示例:

*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
Run Code Online (Sandbox Code Playgroud)

有关示例的一些注意事项:

  • StringIntPair是一种类型 ; 做:t <expression>在解释示出了表达式的类型
  • StringInt并且IntString是相同类型的构造函数
  • vertical bar(|)分隔构造函数
  • 一个编写良好的函数应该匹配其参数类型的每个构造函数; 这就是为什么我combine用两种模式编写的,每种模式一种

  • Haskell中的数据构造函数不会做任何事情.(它完全不同于C++或Java中的构造函数).它只是一个标记你打了一堆数据,以区别于其他数据束.`StringInt"abc"123`是一个`String`和一个`Int`,用`StringInt`标记. (3认同)
  • @wvxvw是的,你需要定义一个构造函数!在`data StringIntPair = StringInt String Int`中,**`StringInt String Int`**是一个构造函数,它接受两个参数,一个`String`和一个`Int`(按顺序!).我不知道我是否完全理解你的第二个问题; 您可能希望将其作为单独的问题发布,以获得更完整的答案. (2认同)

ДМИ*_*КОВ 7

data StringIntPair = StringInt String Int
                   | IntString Int String

combine :: StringIntPair -> String
combine (StringInt s i) = s ++ (show i)
combine (IntString i s) = (show i) ++ s
Run Code Online (Sandbox Code Playgroud)

所以它可以这样使用:

> combine $ StringInt "asdf" 3
"asdf3"
> combine $ IntString 4 "fasdf"
"4fasdf"
Run Code Online (Sandbox Code Playgroud)