【发布时间】:2022-01-23 06:34:18
【问题描述】:
以下代码来自https://www.manning.com/books/real-world-functional-programming第8章
当我运行代码时,我在 testClientTree 中收到空引用异常。我检查了这本书的勘误表,但没有找到任何内容。
type Client =
{ Name : string
Income : int
YearsInJob : int
UsesCreditCard : bool
CriminalRecord : bool }
let john =
{ Name = "John Doe"
Income = 40000
YearsInJob = 1
UsesCreditCard = true
CriminalRecord = false }
type ClientTests =
{ Check : Client -> bool
Report : Client -> unit }
type QueryInfo =
{ Title : string
Test : Client -> bool
Positive : Decision
Negative : Decision }
and Decision =
| Result of string
| Query of QueryInfo
let rec tree =
Query({ Title = "More than $40k"
Test = (fun cl -> cl.Income > 40000)
Positive = moreThan40; Negative = lessThan40 })
and moreThan40 =
Query({ Title = "Has criminal record"
Test = (fun cl -> cl.CriminalRecord)
Positive = Result("NO"); Negative = Result("YES") })
and lessThan40 =
Query({ Title = "Years in job"
Test = (fun cl -> cl.YearsInJob > 1)
Positive = Result("YES"); Negative = usesCredit })
and usesCredit =
Query({ Title = "Uses credit card"
Test = (fun cl -> cl.UsesCreditCard)
Positive = Result("YES"); Negative = Result("NO") })
let rec testClientTree(client, tree) =
match tree with
| Result(msg) ->
printfn " OFFER A LOAN: %s" msg
| Query(qi) ->
let s, case = if (qi.Test(client)) then "yes", qi.Positive
else "no", qi.Negative
printfn " - %s? %s" qi.Title s
testClientTree(client, case)
[<EntryPoint>]
let main argv =
testClientTree(john, tree)
0
【问题讨论】:
-
您可以通过简单地从
tree和以下三个定义中删除rec和and来修复它 - 将它们简化为let- 并重新排序四个以使其全部编译. -
有很多多余的括号是不需要的,并且使代码更难阅读。
标签: f#