比较f#中两个单独列表中的项目

时间:2013-02-22 12:17:24

标签: list f# compare

这是我正在研究的例子:

    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来比较每个人的测试,并确定他们得到了多少答案。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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)]

答案 2 :(得分:0)

通过获得好的和错误的答案计数来扩展一点这将有效......

首先map处理每个单独得分列表的结果。然后使用正确的awnserlist fold2找到matches(你可以使用简单的if if here)。我在tuple中计算了好的和错误的答案数。 show函数执行一个简单的iter来获取元组中的第一个和第二个项目,然后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#interactive运行:

show (scores test answers);;
Andy correct: 12 wrong: 4 
Harry correct: 5 wrong: 11