Those are some lists:
Prelude> [1,2]
[1,2]
Prelude> [1,2,3]
[1,2,3]
Hera are some tuples:
Prelude> (1,2)
(1,2)
Prelude> (1,2,3)
(1,2,3)
Prelude> (1,2,3,4)
(1,2,3,4)
List and tuple
There are two differents between list and tuple:
- List can compare the length. Tuple cannot compare the length.
Prelude> [1,2] == [1,2,3]
False
Prelude> (1,2) == (1,2,3)
<interactive>:26:10: error:
• Couldn't match expected type ‘(Integer, Integer)’
with actual type ‘(Integer, Integer, Integer)’
• In the second argument of ‘(==)’, namely ‘(1, 2, 3)’
In the expression: (1, 2) == (1, 2, 3)
In an equation for ‘it’: it = (1, 2) == (1, 2, 3)
- All of the elements in a list must be the same type, the elements in the tuple can be of different type.
Prelude> [1,"two"]
<interactive>:27:2: error:
• No instance for (Num [Char]) arising from the literal ‘1’
• In the expression: 1
In the expression: [1, "two"]
In an equation for ‘it’: it = [1, "two"]
Prelude> (1,"two")
(1,"two")
Functions
- fst gives the first element
- snd gives the second element
Prelude> fst ("Wow", False)
"Wow"
Prelude> snd ("Wow", False)
False
Note:这两个函数仅对序对有效,而不能应用于三元组,四元组和五元组之上。
- zip can zip those lists togther
Prelude> zip [1,2,3,4,5] [5,5,5,5,5]
[(1,5),(2,5),(3,5),(4,5),(5,5)]
Here is a haskell program to find a right triangles:
let rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24]
Prelude> rightTriangles'
Note: 我们可以使用 let
关键字来定义一个常量。在 ghci 下执行 let a=1
与在脚本中编写 a=1
是等价的。