Haskell Study Note 7 : Tuple
Haskell Study Note 7 : Tuple
Tuple
Tuple can have different types of values.
-
Common form :
(String, Int)、(Bool, Double, String)like :
("Alice", 20) -
Pair & Triple :
1
2
3
4
5-- Pair
("Alice", 20)
-- Triple
("Bob", 25, "Engineer")
Basic operations of a Tuple
-
Create a tuple :
1
2student :: (String, Int)
student = ("Tom", 18) -
Pattern matching & Usage within a function:
1
2getStudentInfo :: (String, Int) -> String
getStudentInfo (name, age) = "Name: " ++ name ++ ", Age: " ++ show age -
Pair operations :
fstandsnd, like :1
2
3
4
5
6
7
8
9
10
11
12
13
14student = ("Emma", 21)
main = do
print (fst student) -- 输出 "Emma"
print (snd student) -- 输出 21
ADT = Algebraic Data Type
To define a ADT :
```haskell
data Product = Item String Int
Explain :
Itemis a constructorProductis a new Type name
For instance, if we create a good card :
1 | notebook :: Product |
To read an ADT, we can use pattern matching :
1 | describeProduct :: Product -> String |
Practice
1 | data Product = Item String Int |
Note:
- To define data, you can write outside the main, as it is a type
- data as a parameter : you should use
()andItem, then you name each elements, just like other common variables - data as return values : you should use Item
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 zhangxixi的博客!
