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
    2
    student :: (String, Int)
    student = ("Tom", 18)
  • Pattern matching & Usage within a function:

    1
    2
    getStudentInfo :: (String, Int) -> String
    getStudentInfo (name, age) = "Name: " ++ name ++ ", Age: " ++ show age
  • Pair operations :

    fst and snd , like :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
        student = ("Emma", 21)

    main = do
    print (fst student) -- 输出 "Emma"
    print (snd student) -- 输出 21

    ## ADT

    ADT = Algebraic Data Type

    To define a ADT :

    ```haskell
    data Product = Item String Int

Explain :

  • Item is a constructor
  • Product is a new Type name

For instance, if we create a good card :

1
2
notebook :: Product
notebook = Item "Notebook" 50

To read an ADT, we can use pattern matching :

1
2
3
describeProduct :: Product -> String
describeProduct (Item name price) =
"Product: " ++ name ++ ", Price: " ++ show price

Practice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
data Product = Item String Int

pen :: Product
pen = Item "pen" 5

eraser :: Product
eraser = Item "eraser" 3

notebook :: Product
notebook = Item "notebook" 20

readTheProduct :: Product -> String
readTheProduct (Item name price) = "Name: " ++ name ++ " Price: " ++ show price ++ "\n"


main :: IO ()
main = do
putStr (readTheProduct pen)
putStr (readTheProduct eraser)
putStr (readTheProduct notebook)

Note:

  1. To define data, you can write outside the main, as it is a type
  2. data as a parameter : you should use () and Item, then you name each elements, just like other common variables
  3. data as return values : you should use Item