Haskell趣学指南-学习笔记(9)

Curried functions
函数的回传
下图中的两个式子,输出的结果相同。
下一行的式子是上一行的实际运算过程。
即用5去调用max 4,得出结果5。
ghci> max 4 5
5
ghci> (max 4) 5
5

1、下图可以转换,两边都可以省略掉x。

compareWithHundred :: (Num a, Ord a) => a -> Ordering
compareWithHundred x = compare 100 x
compareWithHundred :: (Num a, Ord a) => a -> Ordering
compareWithHundred = compare 100

2、下图为高端函数示例:将一个函数做为另一个函数的参数。

applyTwice :: (a -> a) -> a -> a
applyTwice f x = f ( f x )

 实际是的运算过程是,先用 x 去调用 f ,得到的值再去调用 f 。(这里可以与1参照,x 是去调用别的函数的参数,放置在最右边,所以在1中省略后,也是把x放在最右边考虑的。

ghci> applyTwice (+3) 10
16
ghci> applyTwice (++ " HAHA") "HEY"
"HEY HAHA HAHA"
ghci> applyTwice ("HAHA " ++) "HEY"
"HAHA HAHA HEY"
ghci> applyTwice (multThree 2 2) 9
144
ghci> applyTwice (3:) [1]
[3,3,1]
applyTwice (multThree 2 2) 9

 先用9去调用multThreee 2 2,得到36,然后再用36再去调用multThreee 2 2。

高端函数

zipWith‘

zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ _ [] = []
zipWith' _ [] _ = []
zipWith' f (x:xs) (y:ys) = f x y : zipwith' f xs ys
ghci> zipWith' (+) [4,2,5,6] [2,6,2,3]
[6,8,7,9]
ghci> zipWith' max [6,3,2,1] [7,3,1,5]
[7,3,2,5]
ghci> zipWith' (++) ["foo ","bar ","baz "] ["fighters","hoppers","aldrin"]
["foo fighters","bar hoppers","baz aldrin"]
ghci> zipWith' (*) (replicate 5 2) [1..]
[2,4,6,8,10]
ghci> zipWith' (zipWith' (*)) [[1,2,3],[3,5,6],[2,3,4]] [[3,2,2],[3,4,5],[5,4,3]]
[[3,4,6],[9,20,30],[10,12,12]]

 flip’

flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f = g
    where g x y = f y x

可以简写为:括号的省略是因为 -> 为向右结合,where的省略目前还不明白

flip' :: (a -> b -> c) -> b -> a -> c
flip' f y x = f x y

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值