A******g 发帖数: 612 | 1 (define (calc2 exp)
(match exp
[ (? number? x) x ]
)
)
作用是如果exp是一个数字,就返回这个数字
不明白这个 (? number? x) 是什么用法,猜意思就是把exp赋值给x, 然后判断x是不是
数字
但是这个到底是什么用法,还请FP高手解释一下 |
p*****2 发帖数: 21240 | |
A******g 发帖数: 612 | 3 有道理,但是
(? ... ) 是什么用法? 是只能和match搭配的特定用法吗? |
p*****2 发帖数: 21240 | 4
我不懂scheme的语言。是它的syntax吗?
【在 A******g 的大作中提到】 : 有道理,但是 : (? ... ) 是什么用法? 是只能和match搭配的特定用法吗?
|
A******g 发帖数: 612 | 5 应该是,这个标点符号作语句,都很难google... |
t****a 发帖数: 1212 | 6 刚在racket(一种scheme解释器)里尝试了一下
> (define (calc2 exp)
(match exp
[ (? number? x) x ]
)
)
> (calc2 10)
10
> (calc2 "abc")
match: no matching clause for "abc"
> (calc2 true)
match: no matching clause for #t
楼主说的大概是对的
稍微改了一下函数,加了判断string的
> (define (calc2 exp)
(match exp
[ (? number? x) x ]
[ (? string? x) x ]
)
)
> (calc2 "abc")
"abc"
更多的pattern match这里有
http://docs.racket-lang.org/reference/match.html
里面有些很有趣的用法
不过不知道它怎么实现的,因为[ (? number? x) x ]这个玩意既不是函数又不是值,
大概match本身是个宏也说不定。有懂行的朋友给解释一下吗? |
f*******n 发帖数: 12623 | 7 scheme里没有pattern match。你是说racket自己的吧? |
e*******o 发帖数: 4654 | 8 http://ceaude.twoticketsplease.de/articles/an-introduction-to-l
Conveniently, the ? operator is an implicit and operator, so instead of:
(and (? foo?) x)
we can instead write:
(? foo? x)
我碰巧看到转过来。 |
e*******o 发帖数: 4654 | 9 (? expr pat ...) — applies expr to the value to be matched, and checks
whether the result is a true value; the additional pats must also match; i.e
., ? combines a predicate application and an and pattern. However, ?, unlike
and, guarantees that expr is matched before any of the pats. |