Haskell 2

纪正德
2023-12-01

haskell默认x:xs中x是首元素,xs是剩余的,若想xs是末尾元素,可以先reverse列表

Not in scrope 没定义

Not instance for …类型错误

对于递归,[1,”asdf”,24] ++ [],结果还是[1,”asdf”,24]

定义变量保存数据,若是局部变量,用where n = ,全局变量则直接在函数底部 n = ,注意不要用出现过的标识符

!!从列表取出元素,take取出列表

say :: String -> String

sayit :: String -> IO ()

sayit = putStr . say等价于sayit string = putStr (say string)

若有多个函数,定义时直接写结果,say1 :: String -> String

say1 x =take’ 1 (putLetter (take 1 x))

因为String可以看作[Char],所以对于List的函数也可以对字符串

当希望分母为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
得到
#
##
###

水平拼接

type Picture = [String]

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

上下翻转(只要有换行,如[“#”’
“##”,
“###”],第一个元素与最后一个交换,可得到上下翻转)

当字符串出现\n时,用putStr会打出回车,所以把字符串列表写成上式形式没有意义,可表示成[“#\n”’”##\n”,”###\n”]

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.

 类似资料:

相关阅读

相关文章

相关问答