haskell iterate 迭代示例

准备知识

一些系统函数
添加库 :m + Data.Char
减去库 :m - Data.Char
digitToInt ('0...f'--->0---15)
IntTodigit 反一下

ord (字符-->ascii码)
chr (ascii-->字符)

 map digitToInt "24324aadddf"
[2,4,3,2,4,10,10,13,13,13,15]


例题

1 生成从a开始的字母序列

 take 3  (iterate (\x-> [intToDigit (digitToInt (head x)+1) ] )  ['a'])

["a","b","c"]


2 生成形如[a,b....c]的等差数列

func :: Int->Int->Int->[Int]

func a b c = if (b<=a)  then takeWhile(>=c) (iterate (+(b-a)) a) else takeWhile(<=c) (iterate (+(b-a)) a)


3 整数转字符串  45->"45"

showint1 = map chr.map(+48).reverse.map(`mod` 10).takeWhile(/=0).iterate(`div` 10)


let showint n= map (intToDigit ) (reverse (map (`mod` 10 ) (takeWhile (/=0)  ( iterate ( `div` 10 )  n))))

4 字符串转整数

 getint1 n = foldl f 0  (map(+(-48)) (map ord n)) where f x y = x*10+y

 let getint n = last  (scanl (\x y -> x*10+y) 0  (map (digitToInt )  (map (head)  (takeWhile (/="")  (iterate (drop 1) n)))))

你可能感兴趣的:(haskell iterate 迭代示例)