【问题标题】:Why do I keep getting errors in this piece of code for Standard ML?为什么我在标准 ML 的这段代码中不断出现错误?
【发布时间】:2012-10-23 04:13:25
【问题描述】:

我正在学习标准机器学习,但我不断收到此错误,我不知道为什么?

这是代码和错误:

> fun in_list(element, list) = 
    if hd(list) = element then true
    else val tempList = List.drop(list, 1);
    in_list(element, tempList);
# # Error-Expression expected but val was found
Static Errors

我知道我尝试的语法一定有问题。

【问题讨论】:

    标签: sml ml


    【解决方案1】:

    您需要将 val 值包装在 let..in..end 块中。

    fun in_list(element, list) = 
        if hd(list) = element then true
        else 
            let
               val tempList = List.drop(list, 1)
            in
               in_list(element, tempList)
            end
    

    此外,不建议将hddrop 分解为列表。您应该改用模式匹配。

    fun in_list(element, x::xs) = 
        if x = element then true
        else in_list(element, xs)
    

    有一个缺少空列表的基本情况,您可以使用orelse替换if x = element then true ...。我把它们留给你作为建议。

    【讨论】:

    • 太棒了,x::xs 是做什么的?我知道“::”表示缺点。还有我怎样才能让它返回false?
    • :: 是 cons 构造函数,用于将非空列表分解为头部 x 和尾部 xs。使用空列表[]:: 构造一个列表。例如,[1, 2, 3] 实际上是 1::2::3::[]
    • 好吧,有道理,如果不是真的,我怎样才能让函数返回假,因为我们使用“then”关键字来返回真案例。
    • 好吧,正如我在回答中所说,您错过了基本案例fun in_list(element, []) = false | in_list(element, x::xs) = ...。如果输入列表为空,您只需返回 false
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多