f# - This expression was expected to have type xxxx but here has type unit -
the following code has type error both of printfn
s.
how should fix it? i'd seq.map
loop continue if 1 of items fails.
// files should seq of record let files = seqofstrs |> seq.map(fun s -> match s | helper.parseregex "(\w+) xxxxx" month -> let currentmonth = ..... if currentmonth = month.[0] doc.load(shelf) // parse doc , return record type. omitted else printfn "expect %s found %s." currentmonth month.[0] //error | _ -> printfn "no '(month) payment data on line' prompt." //error
the problem different branches of logic producing different things. in "omitted" section you're apparently returning value of type xxxx (e.g. string
), in other branches printfn
calls, you're returning without value, in f# represented unit
, in other languages called void
.
if didn't want loop continue, simplest answer throw exception in cases, e.g:
failwithf "expect %s found %s." currentmonth month.[0]
the static return type of failwithf
can type @ all, including string
, because never returns doesn't have produce value of type.
given want code continue, instead return empty string or kind of failure value, e.g.:
printfn "expect %s found %s." currentmonth month.[0] //error "failed"
now branches have same type code compile, have careful callers don't accidentally interpret value being valid result, why throwing exception cleaner.
a cleaner approach use option
value represent success or failure, i.e. return some "..."
in correct case , none
in error cases. approach nicer when failure common-place occurrence calling code handle rather reporting problem user , aborting:
// files should seq of record let files = seqofstrs |> seq.map(fun s -> match s | helper.parseregex "(\w+) xxxxx" month -> let currentmonth = ..... if currentmonth = month.[0] doc.load(shelf) // parse doc , produce record type. record else printfn "expect %s found %s." currentmonth month.[0] //error none | _ -> printfn "no '(month) payment data on line' prompt." //error none
you need decide want files
contain @ point - want explicit none
value show failed, or want sequence contain correct values , omit failures entirely?
if want explicit values, can leave option
values in place , you'll have seq<string option>
result. note type syntactic sugar seq<option<string>>
, reflecting f#'s o'caml heritage.
if want omit them, replace seq.map
call seq.choose
, drop none
values , strip off some
wrappers, leaving seq<string>
current code trying produce.
Comments
Post a Comment