【问题标题】:Basic f# error - pattern matching is implying the wrong type基本 f# 错误 - 模式匹配意味着错误的类型
【发布时间】:2013-06-20 13:37:08
【问题描述】:

以下代码采用 2 个参数。第一个是三元组列表:三元组 (d,m,y) 用于表示日期。

第二个是一个月的整数

该代码用于计算列表中该月份的日期出现次数

附言我想这可能看起来像一个家庭作业问题 - 它不是。它来自我今年早些时候在 ML 中完成的一门课程,我正在尝试重做 f# 中的所有练习。所以这只是为了我的利益

let rec number_in_month (dates : (int * int * int) list, month) =  
    match dates with
    | [] -> 0
    | (_,y,_) when month = y -> 1 + number_in_month(dates.Tail, month)
    | _ -> number_in_month(dates.Tail, month)

但它给出了错误:

这个表达式应该有类型 (int * int * int) 列表但这里有类型 'a * 'b * 'c

知道我做错了什么吗?

【问题讨论】:

  • 实际上,输入您的列表 intintint 没有任何价值,是吗?你就不能做到(dates : ('a* 'b* 'c) list 吗?
  • 如果我这样做,我会得到一个类似的错误:这个表达式应该有类型 ('a * 'b * 'c) 列表,但这里有类型 'd * 'e * 'f跨度>

标签: f#


【解决方案1】:

您的第二个模式匹配试图匹配单个日期(_,y,_),但它正在与您的日期列表匹配。尝试改用(_,y,_)::_ 进行匹配。

更惯用的方法是使用(_,y,_)::tail 进行匹配,并在表达式后面使用tail 而不是dates.Tail

【讨论】:

  • 啊 - 当然 - 现在你指出来这很有意义 - 谢谢。另外 - 我怀疑我错误地定义了参数?因为如果我将它们放在括号中,它们是一个元组,对吗?作为常规柯里化函数,正确的做法是什么?
  • 只是空格而不是括号\逗号。
【解决方案2】:

代码也可以收紧(包括 MarkP 建议的修复)。注意使用类型推断,这样dates的类型就不需要传递了

let rec number_in_month dates month = 
    match dates with
        | [] -> 0
        | (_,y,_)::tail ->       
           ( number_in_month tail month) + (if y = month then 1 else 0)


let data = [(1,2,3);(1,2,3);(1,5,7);(1,9,2);(1,9,2);(1,9,2)]

number_in_month data 5
number_in_month data 2

http://www.tryfsharp.org/create/bradgonesurfing/datefinder.fsx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2015-03-18
    • 2016-01-17
    相关资源
    最近更新 更多