SML:语法错误在哪里

Fro*_*eet 1 sml

所以我最近学习了sml,并且与java相比如何使用它真的很困惑.所以我被告知我制作一个代码,它接受连续的值对,添加它们并将总和插入到新的列表中.

如果原始列表具有奇数长度,则第一个n-1项目成对添加,并且该n-th项目仅按原样复制到新列表的末尾.

所以到目前为止我的代码是:

fun sumpairs x =

    if null x then []
    else (if (tl x =[]) then x
    else hd x + hd(tl x) :: sumpairs(tl (tl x));

sumpairs([1,2,3]); (I want to test it on this to get something like [3,3])
Run Code Online (Sandbox Code Playgroud)

但我收到语法错误.而且由于sml没有为我找到错误,我会在问题上失败,或者它是否有效.我相信这应该有效.

mol*_*ilo 5

你有一个不匹配的括号(if (tl x =[]).
(SML的错误消息可能是我遇到的最令人困惑的 - 我在EOF中得到"语法错误",这完全没用.)

如果使用更少的内容,则更容易匹配括号:

fun sumpairs x =
    if null x then []
    else if tl x = [] then x
    else hd x + hd (tl x) :: sumpairs (tl (tl x))
Run Code Online (Sandbox Code Playgroud)

可以显示哪些括号匹配的编辑器也有帮助.
如果您找到了神奇的设置,大多数现代程序员的编辑都可以做到这一点.

我建议您对模式匹配感到满意 - 使用模式跟逻辑比使用条件链更容易:

fun sumpairs [] = []
  | sumpairs [x] = [x]
  | sumpairs (x::y::xs) = x + y :: sumpairs xs
Run Code Online (Sandbox Code Playgroud)