lambda in F#

F#中的lambda表达式很容易给人造成误解,好象它只支持单行的语句,其实不然,它是可以支持多行的,比如

let f = (fun () ->
    (printf "hello"
     printfn " world"
    ))

只是上面这种写法实在太过难看,所以一般推荐写成一行,语句之间用分号隔开,

let f = (fun() -> ( printf "hello"; printfn "world"))。

 

当然用分号隔开的可读性也不好,比如用F#来实现的SICP 3.1节中的make-withdraw,读起来还是很让人头痛的。

 

let makewithdraw (balance:int) = 
    
let refb = ref balance
    
fun amount -> ( if !refb >= amount then refb := !refb-amount; !refb; else failwith "Insufficient funds")

 

 

 

posted @ 2009-12-28 00:15 芭蕉 阅读(104) 评论(2) 编辑 收藏

 回复 引用 查看   
#1楼 2009-12-28 01:03 地狱门神      
其实这么写就行了
let f = fun () ->
    printf "hello"
    printfn "world"

let makewithdraw (balance:int) = 
    let refb = ref balance
    fun amount ->
        if !refb >= amount then
            refb := !refb-amount
            !refb
        else
            failwith "Insufficient funds"


 回复 引用 查看   
#2楼[楼主] 2009-12-28 10:50 芭蕉      
@地狱门神
嗯,可读性更好一些。
我习惯用括号了...