Haskell--Tuples

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:

  1. 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)
  1. 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 是等价的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值