mushroompot

mushroompot

全栈,全干,全菜。 be a fullstack man, just for fun!
twitter

函數式三板斧(map,filter,fold)

什麼是 map, filter, fold#

map#

map 接受一個函數和一個列表,並將函數應用於列表中的每個元素,最後返回應用函數後的列表。

在 Haskell 中,map 的型別簽名為
map :: (a -> b) -> [a] -> [b]

Racket 代碼
(define (mymap function mylist)
  (cond
     ((null? mylist) '())
     (else (cons (function (car mylist)) (mymap function (cdr mylist)) ))
  )
)
(define (add2 x) (+ 2 x))
(mymap add2 '(1 2 3 4 5 6 7 8))

=> (3 4 5 6 7 8 9 10)

filter#

顧名思義,將列表中符合條件的值提取出來

在 Haskell 中,filter 的型別簽名為
filter :: (a -> Bool) -> [a] -> [a]

Racket 代碼
(define (myfilter condition? mylist)
  (cond
    ((null? mylist) '())
    ((condition? (car mylist)) (cons (car mylist) (myfilter condition? (cdr mylist))))
    (else (myfilter condition? (cdr mylist)))
  )
)

(define (odd? a)
  (eq? (modulo a 2) 1)
)

(myfilter odd? '(-1 -2 -3 -4 -5 -6 -7 -8 -9 -10))
=> (-1 -3 -5 -7 -9)

fold#

fold 就是折疊的含義,一般來說可以分為左折疊和右折疊

我們以左折疊(foldl)為例

在 Haskell 中,foldl 的型別簽名為
foldl :: (a -> b -> a) -> a -> [b] -> a

Racket 代碼
(define (myfoldl base function mylist)
  (cond
     ((null? mylist) base)
     (else (myfoldl (function base (car mylist)) function (cdr mylist)))
  )
)

(define (add x y)
  (+ x y)
)

(myfoldl 0 add '(1 2 3 4 5 6 7 8 9))
=> 45
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。