首页 > 解决方案 > 如何在 F# 中使用匹配 Map 元素?

问题描述

我试图创建一个函数,它接受两个整数 a,b 作为输入,如果 a=1 b=2 则返回 5,否则返回 6,这就是我所做的:

let examplef (a:int), (b:int)=
    match a,b with
    |1,2 -> 5
    |_,_->6;;

它给出了这个错误:“模式鉴别器'examplef'没有定义。”

我问这个问题是因为这段代码中的错误:

type Team = string 
type Goals = Goals of int 
type Points = Points of int 
type Fixture = Team * Team 
type Result = (Team * Goals) * (Team * Goals) 
type Table = Map<Team,Points>

let league =["Chelsea"; "Spurs"; "Liverpool"; "ManCity"; "ManUnited"; "Arsenal"; "Everton"; "Leicester"]

let pointsMade (a: Result)=
    match a with
    |((b,Goals bg),(c,Goals cg))-> if b<c then ((b,Points 0),(c, Points 3))
                                   elif b=c then ((b,Points 1),(c,Points 1))
                                   else ((b, Points 3),(c, Points 0))

尝试定义以下函数时出现错误:

let updateTable (t:Table, r: Result)= 
    let pointmade = pointsMade r
    match pointmade with
    |((f,Points s),(f1,Points s1))-> match Map.tryFind f t  Map.tryFind f1 t with
                                    |None, None -> t
                                    |Some Points x, Some Points y ->t .Add (f, Points s+x1) .Add(f1, Points s1+y1)

当我将鼠标悬停在第一个“Map.tryFind f t”上时,它说“这个值不是一个函数,不能应用。此外,还有一个错误,t .Add (f, Points s+x1) .Add(f1, Points s1+y1)它说:“连续的参数应该用空格和元组和参数分隔涉及函数或方法应用的应加括号”。请帮忙

标签: f#

解决方案


看起来你混淆了元组和咖喱参数。

带有单个元组参数的示例(需要括号)。

签名:int * int -> int

//let example1 (a: int, b:int) = 
let example1 (a, b) =
    match a, b with
    | 1, 2 -> 5
    | _    -> 6

//let example2 (t: int * int) =
let example2 t =
    match t with
    | 1, 2 -> 5
    | _    -> 6 

带有两个咖喱参数的示例:

签名:int->int->int

//let example3 (a: int) (b: int) = 
let example3 a b =
    match a, b with
    | 1, 2 -> 5
    | _    -> 6

推荐阅读