f# - 如何在 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)
它说:“连续的参数应该用空格和元组和参数分隔涉及函数或方法应用的应加括号”。请帮忙
解决方案
看起来你混淆了元组和咖喱参数。
带有单个元组参数的示例(需要括号)。
签名: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
推荐阅读
- c++ - C ++中的属性和pragma有什么区别?
- python - Python C 扩展如何测试引用计数和内存泄漏?
- python - beautifulsoup 抓取表,缺少链接名称
- swift - 来自 Reality Composer 的 SwiftUI 和 RealityKit 触发动作
- excel - 如果“=”有多个值怎么办?
- python-3.x - seaborn的PairGrid方法中调整网格x轴刻度和y轴刻度
- azure-devops - 哪些功能(如果有)与 Azure DevOps 的功能和史诗中的“开始日期”和“目标日期”字段相关联?
- python - 不知道如何在 python3 flask 网站上同时处理多个用户
- c - 编译器优化导致按位移位的奇怪行为
- java - 无法将数据发送到 Firestore