处理SML中“ref”的递归函数

问题描述 投票:0回答:1

这是我的第一个递归函数;我是编程世界的新手。所以,

the code does really confuse me. I discovered that SML doesn't allow
变量更新。所以我学会了使用 ref,代码就是结果。但这仍然是错误的。请告诉我我的代码有什么问题。

我希望这个函数返回第二个参数作为第一个参数列表的每个元组中的第二个整数出现的次数。

 '''
    >
    fun number_in_month (lst: (int*int*int) list, month: int) =
    let val dates = ref 0 : int ref;
    in if null lst
    then !dates
    else 
    let      val tl_ans = tl lst;
             val hd_ans = hd lst; 
             in
             let
             fun add_1(date : int*int*int) =
             if #2 date = month
             then (dates := !dates + 1; !dates)
             else !dates;
             in
             add_1(hd_ans) end
             number_in_month(tl_ans, month);
             end 
    '''
recursion functional-programming ref smlnj
1个回答
0
投票

您不应使用

ref
:=
!

出现的次数是

  • 如果列表为空,则为零
  • 否则:
    • 如果第一个元素匹配,则它比列表尾部出现的次数多一个
    • 否则,它只是列表尾部出现的次数

这是一个非常简单的递归,带有两个条件,并且没有更新变量。
翻译成 SML 留作练习。

© www.soinside.com 2019 - 2024. All rights reserved.