【问题标题】:number_in_month exercisenumber_in_month 锻炼
【发布时间】:2020-02-26 05:39:02
【问题描述】:

我对 SML 很陌生,并且正在做功课。 “编写一个函数 number_in_month,它接受日期和月份列表(即 int)并返回列表中有多少个日期在给定月份中。”

这就是我制定的,看不出有什么问题。请帮忙。

`

    fun number_in_month (dates: (int*int*int) list,month:int) = 
    if ((#2 (hd dates)) = month)
    then val flag=1 flag+number_in_month(tl dates, month) 
    else number_in_month((tl dates),month)`

REPL 告诉我们:用 EQUALOP 替换 VAL。

【问题讨论】:

    标签: smlnj


    【解决方案1】:

    您不能“以这种方式”绑定变量。变量的绑定是一个声明,因此不能在需要表达式的地方完成。

    在这种情况下,您必须使用 let-in-end 表达式

    fun foo x = 
      let 
        val a = 42 
      in 
        a*x
      end 
    

    【讨论】:

      【解决方案2】:

      您的问题是无休止的递归。编译器无法摆脱它,因为独立于结果 if..then..else 你再次运行你的函数 试试这个:

      fun number_in_month (dates: (int*int*int) list,month:int) = 
          if null dates
          then 0
          else if ((#2 (hd dates)) = month)
          then val flag=1 flag+number_in_month(tl dates, month) 
          else number_in_month((tl dates),month)
      

      【讨论】:

        【解决方案3】:

        我试图自己修复它,这就是我的解决方案:

        fun number_in_month (dias: (int*int*int) list,mes:int) = 如果为空 dias 然后 0 else if ((#2 (hd dias)) = mes) 然后让 val flag = 1 + number_in_month(tl dias, mes) 在标志 结尾 else number_in_month((tl dias),mes)

        希望你也可以使用!

        【讨论】:

          【解决方案4】:

          来自 REPL 的错误消息令人困惑,但 Jesper 是正确的,如果您需要在函数中使用赋值语句,您应该使用 let-in-end 表达式。这肯定会让你解决这个错误。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-09-15
            • 2019-11-10
            • 1970-01-01
            • 2021-12-14
            • 1970-01-01
            • 2010-11-27
            相关资源
            最近更新 更多