Haskell --- tuple 操作

版权声明:学习交流为主,未经博主同意禁止转载,禁止用于商用。 https://blog.csdn.net/u012965373/article/details/82938961
// fst返回一个序对的首项。
ghci> fst (8,11)  
8  
ghci> fst ("Wow", False)  
"Wow"

// snd返回序对的尾项。 (tuple只有两个数,因此second,snd)
ghci> snd (8,11)  
11  
ghci> snd ("Wow", False)  
False

// 有个函数很cool,它就是zip。它可以用来生成一组序对(Pair)的List。它取两个List,然后将它们交叉配对,形成一组序对的List。它很简单,却很实用,尤其是你需要组合或是遍历两个List时。如下是个例子:
ghci> zip [1,2,3,4,5] [5,5,5,5,5]  
[(1,5),(2,5),(3,5),(4,5),(5,5)]  
ghci> zip [1 .. 5] ["one", "two", "three", "four", "five"]  
[(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]

// 两个list的长度也可以不一致
ghci> zip [5,3,2,6,2,7,2,5,4,6,6] ["im","a","turtle"]  
[(5,"im"),(3,"a"),(2,"turtle")]

ghci> zip [1..] ["apple", "orange", "cherry", "mango"]  
[(1,"apple"),(2,"orange"),(3,"cherry"),(4,"mango")]

// list与Tuple 混用,如何取得所有三边长度皆为整数且小于等于10,周长为24的直角三角形?首先,把所有三遍长度小于等于10的三角形都列出来:
ghci> let triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]

ghci> let rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]

ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24]  
ghci> rightTriangles'  
[(6,8,10)]


猜你喜欢

转载自blog.csdn.net/u012965373/article/details/82938961