我正在翻译Little Mler中运行此数据类型的函数
type sexp<'T> =
An_Atom of 'T
| A_slist of slist<'T>
and
slist<'T> =
Empty
| Scons of sexp<'T> * slist<'T>
功能
// occurs_in_slist : aVal slist -> int
// checks the number of occurrence for aVal in slist
let rec occurs_in_slist =
function
_, Empty-> 0
| (aVal : 'T), Scons(aSexp, (aSlist : 'T)) ->
occurs_in_sexp (aVal, aSexp) + occurs_in_slist (aVal, aSlist)
and
aVal, An_Atom (bVal) -> if (aVal = bVal) then 1 else 0
| (aVal , A_slist(aSlist)) -> occurs_in_slist (aval, aSlist)
但是,我在第二个函数
中出现此错误error FS0010: Unexpected symbol '->' in binding. Expected '=' or other token.
答案 0 :(得分:5)
在函数定义中,您使用and
关键字来定义一个相互递归的函数集,但是您只为第一个函数指定了名称。它期待and
之后的另一个函数的名称,这就是你得到错误的原因。不幸的是你已经把它遗弃了。
我相信这就是你想要做的事情:
let rec occurs_in_slist = function
| _ , Empty -> 0
| aVal : 'T, Scons(aSexp, aSlist : slist<'T>) ->
occurs_in_sexp (aVal, aSexp) + occurs_in_slist (aVal, aSlist)
and occurs_in_sexp = function
| aVal : 'T, An_Atom(bVal) -> if (aVal = bVal) then 1 else 0
| aVal , A_slist(aSlist) -> occurs_in_slist (aVal, aSlist)
虽然我觉得这里更合适的返回类型应该是bool
。
let rec occurs_in_slist = function
| _ , Empty -> false
| aVal : 'T, Scons(aSexp, aSlist : slist<'T>) ->
occurs_in_sexp (aVal, aSexp) || occurs_in_slist (aVal, aSlist)
and occurs_in_sexp = function
| aVal : 'T, An_Atom(bVal) -> aVal = bVal
| aVal , A_slist(aSlist) -> occurs_in_slist (aVal, aSlist)