当希望分母为0时,可以增加测试数据的约束条件,比如:
prop_x a b = (a /= 0 && b /= 0) ==> a div
b == a div
b
用quick check
首先确保下载的是Haskell-Platform (full)
1. 在代码中 import Test.QuickCheck
2. GHCi 载入代码之后,执行 quickCheck prop_xxx
如果通过测试,它会显示OK Passed 100 Tests 之类的内容
=>用于类型约束
==>用于quickcheck条件限制
如 d>0 ==> (d,d)
my_map :: (a ->b ) ->[a] -> [b] ( 对于函数类型的输入,括号不能省,因为->右结合)
my_map f xs = [f x | x <-xs ]
列表都可以用递归表示,上式可写成
my_map f [] = []
my_map f (x:xs) = f x : map f xs
map :: (a -> b) -> [a] -> [b] (map的作用是将列表中每个元素都用一次函数)
map f [x1, x2, …, xn] == [f x1, f x2, …, f xn]
map f [x1, x2, …] == [f x1, f x2, …]
isEven ::Int -> Bool
isEven x = x mod
2 ==0
my_filter ::[Int] ->[Bool]
my_filter xs = [isEven x | x<- xs] (输入时输入myfilter [Int])
或写成
isEven ::Int -> Bool
isEven x = x mod
2 ==0
my_filter ::(a -> b)-> [a] -> [b] 比写成(Int -> Bool) -> [Int] ->[Bool]更适用
my_filter p xs = [p x | x <- xs] (输入时输入my_filter isEven [Int])
filter :: (a -> Bool) -> [a] -> [a] (filter的作用是将列表中每个元素都判断)
filter p xs = [ x | x <- xs, p x] (若x满足p,则返回真,则这个x符合条件)
putStr “Hello\n”,打印出Hello并换行,putStr的作用是打印字符串
print的作用是打印任何类型
print :: a ->IO () IO()意思是把类型a输出在屏幕上
main = print ([(n, 2^n) | n <- [0..19]]),再次输入main,则打印出结果
helpF :: Picture ->String (::后面的叫type signature类型签名)
helpF [] = []
helpF (x :xs) = x ++ “\n” ++ helpF xs (下面函数的辅助函数)
lines :: String -> [String]
lines “” == []
lines “\n” == [“”]
lines “one” == [“one”]
lines “one\n” == [“one”]
lines “one\n\n” == [“one”,”“]
lines “one\ntwo” == [“one”,”two”]
lines “one\ntwo\n” == [“one”,”two”]
unlines [“one”,
“two”]
<==> one
two
pic1 = [
” #”,
” ##”,
” ###”]
printPic :: [String] ->IO ()
printPic pic = putStr (unlines pic)
输入printPic pic1
得到
#
##
###
水平拼接
sideBySide ::Picture ->Picture ->Picture
sideBySide p1 p2 = [ x++y | (x,y) <- zip p1 p2]
或
sideByside [] qs = []
sideByside ps [] = []
sideByside (p:ps) (q:qs) = (p++q) : sideByside ps qs
水平翻转
flipV :: Picture ->Picture
flipV pic = [reverse x | x <-pic]
或者flipV pic = map reverse pic
上下翻转(只要有换行,如[“#”’
“##”,
“###”],第一个元素与最后一个交换,可得到上下翻转)
flipH :: Picture ->Picture
flipH pic = reverse pic
ord :: Char -> Int
ord ’a’
97
ord ’A’
65
chr :: Int -> Char
chr 65
’A’
isUpper :: Char -> Bool(判断是否是大写字母)
isLowr :: Char -> Bool(判断是否是小写字母)
module
1. 在ghci中我们可以用命令:info来查看某个操作符的优先级
2. Not in scope: `a’ , 指a未定义
3.