F#基础知识:地图地图?

时间:2016-04-12 02:18:47

标签: dictionary f#

我的教授给出了我们关于解决问题的课程提示,并建议我们首先使用以下方法对课程进行建模:

let students = Map.add 1 Map.empty Map.empty

世界从一个学生开始(由他们的ID表示,例如1),每个学生都有许多班级ID,每个班级都有一个与他们相关的成绩(A +,F等)。

我无法理解这段代码的实际含义,我理解一张地图。例如

let student = Map.add 43 "A+" 

如何在建议的版本中添加新的“学生”或“classID / grade”并返回新地图?

作为后续内容,我如何在这样的地图上访问/迭代元素? 谢谢,函数式编程初学者在这里真的很挣扎。

4 个答案:

答案 0 :(得分:1)

好的,所以我想出了如何添加它,我只需要给每个Map一个表名,例如

let students = Map.add 1 (Map.add 43 "A+" Map.empty) Map.empty

我可以使用Let student1 = Map.find 1 students来获取特定学生的地图。

答案 1 :(得分:1)

let grades = Map.empty<string,string>
let students = Map.empty<int,Map<string,string>>
let students = students.Add(1,grades.Add("class1","A").Add("class2","B"))
let students = students.Add(2,grades.Add("class3","A").Add("class4","C"))

您可以通过索引到地图来访问该值: students.[1]将返回val it : Map<string,string> = map [("class1", "A"); ("class2", "B")]

另外两条评论:1)通常你会首先构建某种数据结构,例如元组列表,然后从那里构建地图。

let classes = [("class1","A");("class2","B")]
classes |> Map.ofList

2)你可以通过Map.iter或Map.map迭代地图:

let classes' = classes |> Map.ofList

并防止等级膨胀: - )

classes' |> Map.map (fun key value -> (key,value+"-"))

请查看:https://en.wikibooks.org/wiki/F_Sharp_Programming/Sets_and_Mapshttps://msdn.microsoft.com/en-us/library/ee353880.aspx

答案 2 :(得分:1)

虽然我能理解答案,但在尝试s952163(重复变量声明)的答案时出现语法错误,所以我想发布一个可能有用的替代方法。

希望代码中的注释解释了这些建议。

// Alias the types for ease of use later
let studentRecords = Map.empty<int, Map<string, string>>
let grades = Map.empty<string, string>

// create a collection of students 
// (note use of aliases here but could use Map.empty<>.Add if preferred)
let students = 
    studentRecords
        .Add(1, grades.Add("class1", "A").Add("class2", "B"))
        .Add(2, grades.Add("class1", "D").Add("class2", "C"))

// can index into the student map by the integer key
// and print out the value of the embedded map based on it's key
let studentId = 1
let className = "class2"
let student1 = students.[studentId]

printfn 
    "StudentId: %i obtained %s in %s" 
    studentId 
    student1.[className] 
    className

// can use Map.map to iterate and obtain some specifics from the embedded map
// eg.  This prints out all students and their grades for "class2"
printfn "%s results:" className
students 
    |> Map.map (fun key value -> printfn "Student %i - %s" key value.[className] )

我刚刚开始使用f#,所以s952163的答案确实帮助我达到了上述目标。希望它为进入这个问题的人增加了进一步的见解。

答案 3 :(得分:1)

关于你的问题let student = Map.add 43 "A+"的含义:Map.add需要3个参数,一个键,一个值和一个要添加的地图。因此,student是一个获取地图的函数,并返回一个新地图,该地图还包含值为43的密钥"A+"

关于数据类型的另一个建议:成绩不是自由格式字符串。您可以使用与域紧密匹配的数据类型使代码更安全。例如,对于成绩,您可以使用

type Grade = 
    | APlus
    | A
    | B
    | F // Omitting the other grades for brevity

如果你这样做并且很好地使用模式匹配,编译器将帮助你检查你可能忽略的角落的代码。同样,您可以避免将识别学生的整数与识别类的整数混合在一起。

[<Measure>]
type StudentID
[<Measure>]
type ClassID
// A class that contains 2 students with IDs 1 and 2
let initialClass = Set.ofList [ 1<StudentID>; 2<_> ]
// Adding a student with ID 3 gives a new class
let classWithNewStudent = initialClass.Add 3<_>

请注意,您只需要在一个位置添加类型注释,并且可以在其余位置使用<_>。这当然不是万无一失的 - 您仍然可以1<StudentID> + 2<StudentID>,但至少您无法使用学生ID索引每班地图。

有了这个,你现在可以为一个班级中的成绩建立地图:

let gradesForClass101 = 
    [ (1<StudentID>, APlus); (2<_>, F) ]
    |> Map.ofList

let gradesForClass206 = 
    [ (3<StudentID>, B); (2<_>, F) ]
    |> Map.ofList
// Here's the student function from your question:
let addStudent43 = Map.add 43<_> APlus
// This is now a new map that contains students 2, 3, 43
let moreGrades = addStudent43 gradesForClass206

使用类内地图,您现在可以定义从classID到studentID到等级的地图:

// This is now a map of maps: For each class, we store 
// a mapping classID -> grades that all students got in this class
let gradesPerClass = 
    [ (206<ClassID>, gradesForClass206); (101<_>, gradesForClass101)]
    |> Map.ofList

您还在一条评论中询问了mutable / immutable - 不完全确定问题是什么,但是这里有两种方法可以为学生ID 2积累成绩,具有不可变和可变的数据结构:

// Compute all grades that student 2 gets
let gradesViaFold = 
    gradesPerClass
    |> Map.fold (fun state _ grades ->
        // We don't need the classID here, so use _ as the second arg
        match grades.TryFind 2<_> with
        // We found a grade for student 2: Add it at the beginning of the list
        | Some grade -> grade :: state
        // Student 2 did not get a grade for this class: leave the state
        // (grades seen so far) empty
        | _ -> state
    ) []
let printGrades g = Seq.iter (printfn "Grade %A") g
do printGrades gradesViaFold

// Compute all grades that student 2 gets, via a mutable list
let gradesMutable = System.Collections.Generic.List<Grade>()
do 
    gradesPerClass
    |> Map.iter (fun _ grades ->
        match grades.TryFind 2<_> with
        | Some grade -> gradesMutable.Add grade
        | _ -> ()
    )
    printGrades gradesMutable

(使用do只是为了突出显示有副作用的部分,在大多数情况下不需要这样做)

以下是另一个如何浏览地图的示例:

// A map from classID to grade for student 2
let gradesForStudent2 = 
    gradesPerClass
    |> Seq.choose (fun (KeyValue(classID, grades)) -> 
        match grades.TryFind 2<_> with
        | Some grade -> Some (classID, grade)
        | _ -> None
    )
    |> Map.ofSeq