类型推断错误

时间:2014-12-22 12:04:34

标签: f# stdin

我有两种类型:

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'

为什么以及如何解决?

1 个答案:

答案 0 :(得分:3)

在表达式中:

List.filter (fun i -> i.Id = id) issues
来自fun用法i

被视为Journal(它是包含Id成员的最后一个类型声明)。你可以玩:

  1. Journal.Id更改为Id2,它会起作用,
  2. 更改JournalIssue的顺序......它会起作用。
  3. 要解决此问题,请将此功能更改为(明确提供类型):

    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