我有两种类型:
type Issue = {
Id: string;
Assigned_To: string;
}
type Journal = {
JournalizedId: string;
Id: string;
UserId: string;
}
我想创建一个函数来获取Issue' s和Id的列表,并返回列表中第一个元素的Assigned_To字段,其中包含Id:
let assignedToOfIssueById (id: string) (issues: Issue list): string =
let issue = List.filter (fun i -> i.Id = id) issues |> List.head
issue.Assigned_To
我收到错误
let issue = List.filter (fun i -> i.Id = id) issues |> List.head
-----------------------------------------------^^^^^^
/Users/demas/stdin(14,48): error FS0001: Type mismatch. Expecting a
Journal list
but given a
Issue list
The type 'Journal' does not match the type 'Issue'
为什么以及如何解决?
答案 0 :(得分:3)
在表达式中:
List.filter (fun i -> i.Id = id) issues
来自fun
用法i
的被视为Journal
(它是包含Id
成员的最后一个类型声明)。你可以玩:
Journal.Id
更改为Id2
,它会起作用,Journal
和Issue
的顺序......它会起作用。要解决此问题,请将此功能更改为(明确提供类型):
let assignedToOfIssueById2 (id : string) (issues : Issue list) : string =
let issue = List.filter (fun (i : Issue) -> i.Id = id) issues |> List.head
issue.Assigned_To
或更好(让filter
从列表中推断出正确的类型):
let assignedToOfIssueById2 (id : string) (issues : Issue list) : string =
let issue = issues |> List.filter (fun i -> i.Id = id) |> List.head
issue.Assigned_To