迭代提供的“列表”有点棘手
我需要对元组元素进行硬编码
我可以在最后做一个列表
与提供的样本不同
((float * char) * (float * char) * (float * char)) list
只有 1 个元素的元组列表
并且鉴于所有元素都属于相同的“种类”
我把它概括为一个
(float*char) list
更容易迭代,更通用
/// Note the absence of comma
/// it's a (float * char) list
let list =
[ (0.1, '*')
(0.5, '@')
(1.0, '!') ]
/// type can't be inferred as parameter
type Tuples = ((float * char) * (float * char) * (float * char)) list
// Type ((float * char) * (float * char) * (float * char)) list
// Note the comma instead of a semicolon
let tuples = [ (0.1, '*'), (0.5, '@'), (1.0, '!') ]
/// Sort by numeric value
let sortByWeight = List.sortBy (fun (x, _) -> x)
/// quite generic recursive function
/// type can't be inferred
let rec isMatch (tuples: (float * char) list) index test =
if index < tuples.Length then
match tuples.[index] with
| (weight, value) when weight > test -> value
| _ -> isMatch tuples (index + 1) test
else
'\000' //can't type ''
/// helper to avoid messing up the index
/// and DRY
let find x list =
isMatch (list |> sortByWeight) 0 x
|> printf "%f -> %A\n" x
printf "With a List\n"
list |> find 0.05
list |> find 0.6
list |> find 2.0
printf "Now with Tuples\n"
/// type can't be inferred
let toList (tuples: Tuples) =
let (a, b, c) = (tuples.Item 0)
[ a; b; c ]
tuples |> toList |> find 0.05
tuples |> toList |> find 0.6
tuples |> toList |> find 2.0
输出
With a List
0.050000 -> '*'
0.600000 -> '!'
2.000000 -> '\000'
Now with Tuples
0.050000 -> '*'
0.600000 -> '!'
2.000000 -> '\000'
到额外的问题...
最简单和更通用的是非递归(查找)
(find1) 更传统,更不通用
(find2) Scott 的递归,更惯用
都做同样的事情,迭代比较并返回一个子产品
let list =
[ (0.1, '*')
(0.5, '@')
(1.0, '!') ]
/// non-recursive
let find test map list =
match list |> List.tryFind test with
| None -> map None
| x -> Some(x).Value |> map
/// iterates
let rec find1 test result index (lst: 'a list) =
if index < list.Length then
match lst.[index] with
| x when test x -> Some(x) |> result
| _ -> find1 test result (index + 1) lst
else
result None
/// iterates , idiomatically
let rec find2 test result index lst =
match lst with
| [] -> result None
| head :: tail ->
if test head then Some(head) |> result
else find2 test result index tail
let greaterThanIndex index = fun (value, _) -> value > index
let map x =
match x with
| None -> '\000'
| Some(_, chr) -> chr
printf "ctrl+c to quit!\n"
// the 'input function'?
match System.Console.ReadLine() with
| input ->
match System.Double.TryParse input with
| false, _ ->
printf "%s: NaN! \n" input
| _, index ->
list
|> find (greaterThanIndex index) map
|> printf "find: %2.2f in %A = %c\n" index list
// ...
list
|> find1 (greaterThanIndex index) map 0
|> printf "find1: %2.2f in %A = %c\n" index list
// ...
list
|> find2 (greaterThanIndex index) map index
|> printf "find2: %2.2f in %A = %c\n" index list