我正在关注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)
这是定义数据类型的一种方法:
data StringIntPair = StringInt String Int |
IntString Int String
deriving (Show, Eq, Ord)
Run Code Online (Sandbox Code Playgroud)
请注意,我为类型定义了两个构造函数StringIntPair,它们是StringInt和IntString.
现在在定义中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是相同类型的构造函数|)分隔构造函数combine用两种模式编写的,每种模式一种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)
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |