0

这是我正在处理的示例:

    let test =
  [("Andy", ["d"; "a"; "d"; "c"; "b"; "d"; "c"; "a"; "a"; "c"; "a"; "d"; "a"; "a"; "d"; "e"]);
   ("Harry", ["b"; "d"; "c"; "b"; "c"; "b"; "a"; "a"; "d"; "b"; "d"; "d"; "a"; "c"; "b"; "e"]);

let answers = ["b"; "a"; "a"; "c"; "d"; "d"; "c"; "a"; "a"; "d"; "a"; "d"; "a"; "a"; "d"; "e"]);

我正在尝试使用 list.map 来比较每个人的测试并确定他们有多少答案是正确的。任何帮助,将不胜感激。

4

3 回答 3

5

我将创建一个函数来计算给定答案列表和正确答案的分数,然后将其应用于列表中的每个元组:

let getScore ans correct = List.map2 (=) ans correct |> List.filter id |> List.length
let getCorrect l = l |> List.map (fun (name, ans) -> (name, getScore ans answers))
于 2013-02-22T12:31:44.517 回答
3

这应该可以解决问题:

let test =
  [("Andy", ["d"; "a"; "d"; "c"; "b"; "d"; "c"; "a"; "a"; "c"; "a"; "d"; "a"; "a"; "d"; "e"]);
   ("Harry", ["b"; "d"; "c"; "b"; "c"; "b"; "a"; "a"; "d"; "b"; "d"; "d"; "a"; "c"; "b"; "e"]); ]

let answerKey = ["b"; "a"; "a"; "c"; "d"; "d"; "c"; "a"; "a"; "d"; "a"; "d"; "a"; "a"; "d"; "e"];

let score answerKey answers =
    List.zip answerKey answers
    |> List.sumBy (fun (key, answer) ->
        if key = answer then 1 else 0)

let results =
    test
    |> List.map (fun (name, answers) ->
        name, score answerKey answers)

如果将其放入 F# Interactive,结果将是:

val results : (string * int) list = [("Andy", 12); ("Harry", 5)]
于 2013-02-22T13:50:49.580 回答
0

通过获得正确和错误的答案计数来扩展一点,这将起作用......

首先映射结果以处理每个单独的记分表。然后使用正确的awnserlist fold2 来查找匹配项(您可以在此处使用简单的 if then )。我计算一个元组中正确和错误答案的数量。show 函数执行一个简单的迭代以从元组中获取第一个和第二个项目,然后printf值。

   let scores results corr = 
    results
    |> List.map ( 
        fun (name, score) -> 
            (name, List.fold2 (
                fun s rhs lhs ->  
                    match s with
                    | (good, wrong) when rhs=lhs -> ( good + 1 , wrong) 
                    | (good, wrong) -> ( good, wrong + 1)
                                ) (0, 0) score corr
            ) 
        )


let show scorelist = 
scorelist
|> List.iter 
    ( fun i -> 
         match i with
         | (name, score) -> 
            match score with
            | (good, wrong) ->
                    printf "%s correct: %d wrong: %d \r\n" 
                     name
                     good 
                     wrong
     )

从 F# 交互式运行:

show (scores test answers);;
Andy correct: 12 wrong: 4 
Harry correct: 5 wrong: 11 
于 2013-02-22T15:27:30.017 回答