「学习总结-Haskell-3] Haskell常用数据结构

来源:互联网 发布:枪战王者辅助软件 编辑:程序博客网 时间:2024/06/15 16:45

Haskell 常用数据结构

Table of Contents

  • 1 Haskell 基本知识
  • 2 Haskell 重要数据结构-List
  • 3 Haskell 常用数据结构
    • 3.1 Tuple是什么
    • 3.2 Pair
      • 3.2.1 Pair 是什么
      • 3.2.2 与Pair有关的函数
    • 3.3 用Tuple编写程序

1 Haskell 基本知识

2 Haskell 重要数据结构-List

3 Haskell 常用数据结构

3.1 Tuple是什么

Tuple就是二元组,三元组,等等,组内元素可以为不同类型,而List元素必须为同一类型

ghci>(1,2)(1,2)ghci>('h','i','j')('h','i','j')ghci>(1,'a',3.5)(1,'a',3.5)

下面这个例子说明了Tuple内元素的类型决定了Tuple的类型,即 (1,2)和('a','b')虽然都是二元组,但是不是同一类型 (1,2)和(1,2,3)虽然元素类型一样,但是数目不同,也不是同一类型

ghci>[(1,2),(3,4),(5,6)][(1,2),(3,4),(5,6)]ghci>[(1,2),('a','b')]errorghci>[(1,2),(3,4,5)]error

3.2 Pair

3.2.1 Pair 是什么

Pair就是二元组

ghci>(1,2)(1,2)ghci>(3,4)(3,4)

3.2.2 与Pair有关的函数

  • fst/snd
ghci>fst (2,3)2ghci>snd (2,3)3
  • zip
ghci>zip [1,2,3] ['a','b','c'][(1,'a'),(2,'b'),(3,'c')]
ghci>zip [1..] ["Apple","Moto","Nokia"][(1,"Apple"),(2,"Moto"),(3,"Nokia")]

3.3 用Tuple编写程序

例1 约束性编程,找出三边在[1,10]内的所有直角三角形

ghci>[(a,b,c) | a <- [1..10], b <- [1..a], c <- [1..b], b^2 + c^2 == a^2][(5,4,3),(10,8,6)]

例2 Tuple与模式匹配

first (x,_,_) = xsecond (_,y,_) = ythird (_,_,z) = z
ghci>first ('a',3,6.7)'a'ghci>second ('a',3,6.7)3ghci>third ('a',3,6.7)6.7

例3

sumPair xs = [x + y| (x,y) <- xs ]
ghci>sumPair [(1,2),(3,4),(5,6)][3,7,11]
sumPair' xs = [z | (x,y) <- xs, let z = x + y]

注意:不能直接写成z = x + y

ghci>sumPair' [(1,2),(3,4),(5,6)][3,7,11]

例4

zip' _ [] = []zip' [] _ = []zip' (x:xs) (y:ys) = (x,y):zip' xs ys
ghci>zip' [1..] ["Apple","***","MI"][(1,"Apple"),(2,"***"),(3,"MI")]



原创粉丝点击