3.3 列表
On this page:
3.3.1 查找
head
3.3.2 合并
concat
zip-with
zip
3.3.3 遍历
foldl
foldr
3.3.4 变换
map
3.3.5 过滤
filter
reject
traverse
filter-map
8.6

3.3 列表

3.3.1 查找

procedure

(head xs)  (Maybe/c any/c)

  xs : (listof any/c)
取出列表的头部。

Examples:
> (head (list))

(Nothing)

> (head (list 1))

(Just 1)

> (head (list "hello" "world"))

(Just "hello")

3.3.2 合并

procedure

(concat xs ys)  (listof a)

  xs : (listof a)
  ys : (listof a)
拼接两条数组。

Examples:
> (concat (list) (list))

'()

> (const (list 1 2 3) (list))

'(1 2 3)

> (const (list 2 3) (list 3 2))

'(2 3)

procedure

(zip-with f as bs)  (listof c)

  f : (-> (a any/c) (b any/c) (c any/c))
  as : (listof a)
  bs : (listof b)
合并两个列表。

(define zip (zip-with cons))

procedure

(zip xs ys)  (listof (cons a b))

  xs : (listof a)
  ys : (listof b)
cons合并。

Example:
> (zip '(1 2 3 4 5) '(a b c))

'((1 . a) (2 . b) (3 . c))

3.3.3 遍历

procedure

(foldl f acc xs)  any/c

  f : (-> any/c any/c any/c)
  acc : any/c
  xs : list?
柯里化的foldl,固定参数长度。

Examples:
> (foldl + 0 (list 1 2 3 4))

10

> (foldl cons (list) (list 1 2 3 4))

'(4 3 2 1)

procedure

(foldr f acc xs)  any/c

  f : (-> any/c any/c any/c)
  acc : any/c
  xs : list?
柯里化的foldr,固定参数长度。

Examples:
> (foldr + 0 (list 1 2 3 4))

10

> (foldr cons (list) (list 1 2 3 4))

'(1 2 3 4)

3.3.4 变换

procedure

(map f xs)  list?

  f : (-> any/c any/c)
  xs : list?
柯里化map,固定参数个数。

Examples:
> (map add1 (list))

'()

> (map add1 (list 1 2))

'(2 3)

3.3.5 过滤

procedure

(filter f xs)  (listof a)

  f : (-> a boolean?)
  xs : (listof a)
(reject f xs)  (listof a)
  f : (-> a boolean?)
  xs : (listof a)
柯里化filterrejectfilter的反面。

Examples:
> (filter even? (list 1 2 3 4 5 6))

'(2 4 6)

> (reject even? (list 1 2 3 4 5 6))

'(1 3 5)

procedure

(traverse f xs)  (Maybe/c (listof b))

  f : (-> a (Maybe/c b))
  xs : (listof a)

Examples:
> (define (get a)
    (->maybe (and (> a 5) a)))
> (traverse get (list 10 11 12))

(Just '(10 11 12))

> (traverse get (list 7 6 5 4 3))

(Nothing)

> (traverse get (list 1 2 10 12))

(Nothing)

> (traverse get (list))

(Just '())

procedure

(filter-map f xs)  (listof b)

  f : (-> a (Maybe/c b))
  xs : (listof a)
同时结合mapfilterf需要返回一个maybe?,如果f返回的是Nothing,就会被过滤出去;最后只留下Just

Examples:
> (filter-map (const nothing) (list 1 2 3))

'()

> (filter-map Just (list 1 2 3))

'(1 2 3)

> (define (f x) (if (even? x) (Just x) nothing))
> (filter-map f (list 1 2 3 4 5 6))

'(2 4 6)