8.6
3.2 Maybe
Nil的安全类型,在类型上避免空指针错误。
3.2.1 Maybe类型定义
“泛型”maybe容器,检测Just是否为a。
Maybe构造器。
同时可用于match。
已确定的Maybe的值。无须再调用生成。
3.2.2 操作
检测是否Maybe。
这引来一个问题,那么我们该如何得到Just #f呢?我的答案是直接调用(Just #f)。
Examples:
> (->maybe 1) (Just 1)
> (->maybe 0) (Just 0)
> (->maybe #f) (Nothing)
> (Just #f) (Just #f)
> (->maybe #t) (Just #t)
Functor映射。
Examples:
Monad的binding。
Examples:
> (define (f x) (Just (add1 x))) > (maybe-then f (Just 1)) (Just 2)
> (maybe-then f nothing) (Nothing)
procedure
(maybe-filter f ma) → (Maybe/c a)
f : (-> a boolean?) ma : (Maybe/c a)
Examples:
> (maybe-filter even? (Just 2)) (Just 2)
> (define (gt xs) (> (length xs) 5)) > (maybe-filter gt (Just (list 1 2 3))) (Nothing)
> (maybe-filter gt (Just (list 1 2 3 4 5 6))) (Just '(1 2 3 4 5 6))
procedure
(maybe-replace x ma) → (Maybe/c)
x : any/c ma : (Maybe/c any/c)
Examples:
> (maybe-replace 1 (Just 2)) (Just 1)
> (maybe-replace "hello" (Just 1)) (Just "hello")
> (maybe-replace "hello" nothing) (Nothing)
Examples:
> (maybe-and (Just 1) nothing) (Nothing)
> (maybe-and (Nothing) (Just 2)) (Nothing)
> (maybe-and (Just 1) (Just 2)) (Just 2)
Examples:
> (maybe-or (Just 1) nothing) (Nothing)
> (maybe-or (Nothing) (Just 2)) (Nothing)
> (maybe-or (Just 1) (Just 2)) (Just 1)
Examples:
> (maybe-alt (Just 1) (Just 2)) (Just 1)
> (maybe-alt (Just 1) (Nothing)) (Just 1)
> (maybe-alt nothing (Just 2)) (Just 2)
Examples:
> (maybe-else 10 add1 (Just 1)) 2
> (maybe-else 10 add1 nothing) 10
Examples:
procedure
(maybe-unwrap x) → y
x : (Maybe/c y)
解包Maybe,遇到nothing直接抛异常。
Examples:
> (maybe-unwrap (Just 1)) 1
> (maybe-unwrap (Just #f)) #f
> (maybe-unwrap nothing) maybe-unwrap: 试图解包nothing!
语法
(maybe-catch expr)
expr = 任何表达式
Examples:
> (maybe-catch (* 1 0)) (Just 0)
> (maybe-catch (/ 1 0)) (Nothing)