Haskell学习笔记--List Comprehension / Data.Char / 凯撒加密问题

List comprehension

序列内涵??恕我英语垃圾翻译不出来

但是它是一种应用在序列上的函数,写起来就像集合一样

相当于是用旧序列生成新序列,不妨翻译为序列生成

比如

[x^2 | x <- [1..10]]
--[1,4,9,16,25,36,49,64,81,100]

[(x,y) | x <- [1..3] , y <- [x..3] ]
--[(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]

 

有个函数 concat

用来把序列套序列的最外层去掉

concat :: [[a]] -> [a]
concat xss = [x | xs <- xss , x <- xs ]

 

Guard

其实就是加上限制条件

factor :: Int -> [Int]
factor n = [x | x <- [1..n] , n `mod` x ==0 ]

isprime :: Int -> Bool 
isprime n = length ( factor n ) == 2 

primes :: Int -> [Int]
primes n = [x | x <- [1..n] , isprime x]

可以喷素数啦

zip:捆绑从头两个列表,舍去匹配不上的

zip 和 Guard 真的是好兄弟啊

sorted :: Ord a => [a] -> Bool 
sorted xs = and [ x <= y  | (x,y) <- zip xs (tail xs)]

positions :: Eq a => a -> [a] -> [Int]
positions s xs = [ i | (x,i) <- zip xs [1..] , x==s]

 

 

Data.Char

两个常用函数:

ord :: Char -> Int 

ord 'a' = 97

chr :: Int -> Char 

chr 97 = 'a'

 

这次课老师布置了一个有点小难的作业:凯撒加密问题

posted @ 2021-11-16 22:05  liankewei123456  阅读(54)  评论(0编辑  收藏  举报