2017-09-13 148 views
0

嗨,我收到以下SML代碼中的編譯錯誤,有人可以幫忙嗎?SML代碼中的錯誤

Error: operator and operand don't agree [UBOUND match] 
    operator domain: 'Z list 
    operand:   ''list 
    in expression: 
    null mylist 
stdIn:4.15-4.24 Error: operator and operand don't agree [UBOUND match] 
    operator domain: 'Z list 
    operand:   ''list 
    in expression: 
    hd mylist 
stdIn:6.19-6.36 Error: operator and operand don't agree [UBOUND match] 
    operator domain: 'Z list 
    operand:   ''list 
    in expression: 
    tl mylist 
stdIn:6.10-7.21 Error: operator is not a function [circularity] 
    operator: 'Z 

表達: (exists_in(項目,TL MYLIST))exists_in

代碼:

fun exists_in (item: ''int, mylist:''list) = 
     if null mylist 
     then false 
     else if (hd mylist) = item 
     then true 
     else exists_in(item, tl mylist) 
    exists_in(1,[1,2,3]); 
+0

我想你是指'int'和'int list'或'''a'和'''列表',而不是''int'和''list'。 – molbdnilo

回答

4

各有什麼錯誤消息告訴你的是,你申請一個功能到某種錯誤的類型。例如,null的類型爲'a list -> bool,因此期望應用於類型爲'a list的參數。在exists_in,你上線應用null''list類型的東西4.

SML還提供了類型推斷,所以沒有真正需要指定類型的參數(雖然它可以用於調試有用)。如果您確實需要指定類型,請按照molbdnilo的評論,您正在查找的類型爲intint list''a''a list'' a是相等類型的一個類型變量)。

無關緊要的是,編寫函數的一種更習慣的方式是通過對列表結構的案例分析來定義它,而不是使用布爾檢查。這樣做的好處是,您立即得到支持布爾檢查的數據,而不管列表是否爲空,而不是檢查並提取數據。例如:

fun exists_in (item, []) = false 
    | exists_in (item, h::t) = (item = h) orelse exists_in (item, t)