F# 強制我未指定的型別為布林值。
我需要 List.find 和 List.tryPick 的組合,并制作了下面的函式。效率并不重要。
'T 型別只能是 bool 型別,我做錯了什么?
let FindPickCombi(list : 'T list, func : 'T -> 'U option) : bool * ('U option) =
(List.find
(fun (x : 'T) ->
match func(x) with
| Some _ -> true
| _ -> false
) list,
List.tryPick(fun x -> func(x)) list)
uj5u.com熱心網友回復:
您自己答案中的當前解決方案在整個串列中回圈兩次。此外,如果沒有找到,第一部分List.find會失敗KeyNotFoundException,這意味著tryPick永遠不會回傳None。
這是另一種選擇,它回傳原始型別list和從您的func. 我們將整個元組包裝在一個option.
let FindPickCombi(list : 'T list, func : 'T -> 'U option) : ('T * 'U) option =
List.tryPick(fun x ->
match func x with
| Some y -> Some(x, y)
| None -> None) list
這可以通過拋棄(list, func)元組來進一步改進,這樣我們的函式就可以使用currying/partial application,這進一步簡化了代碼并且使用了與F#的內置函式相同的引數順序(即:函式引數在前) .
正如您在此處看到的,我們不再有list引數,因為它是List.tryPick由 F# 自動柯里化的:
let FindPickCombi func =
List.tryPick(fun x ->
match func x with
| Some y -> Some(x, y)
| None -> None)
在 FSI 中使用它:
> [1..10] |> FindPickCombi (fun x -> if x = 3 then Some "hello" else None);;
val it: (int * string) option = Some (3, "hello")
'T 型別只能是 bool 型別,我做錯了什么?
您創建了函式的回傳型別bool * 'U option,這就是編譯器強制結果為List.findbool 的原因,這使得 bool'T list串列的型別。
uj5u.com熱心網友回復:
我自己找到了答案。回傳型別不應該是 bool。
將功能更改為:
let FindPickCombi(list : 'T list, func : 'T -> 'U option) : 'T * ('U option) =
(List.find
(fun (x) ->
match func(x) with
| Some _ -> true
| _ -> false
) list,
List.tryPick(fun x -> func(x)) list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/511341.html
標籤:仿制药函数式编程F#
