0

I am learning standard ML and I keep getting this error and I am not sure why?

Here is the code and the error:

> 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

I know there has to be something wrong with the syntax that I am trying.

pad
  • 41,040
  • 7
  • 92
  • 166
cougar
  • 185
  • 5
  • 15

1 Answers1

3

You need to wrap val values in a let..in..end block.

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

Moreover, hd and drop aren't recommended to decompose a list. You should use pattern-matching instead.

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

There is a base case with empty list missing, and you can use orelseto replace if x = element then true .... I leave them for you as suggestions.

pad
  • 41,040
  • 7
  • 92
  • 166
  • Oh cool, what does the x::xs do? i know that "::" means cons. also how to can i get it to return false? – cougar Oct 23 '12 at 18:10
  • `::` is cons constructor which is used to break down a non-empty list to the head `x` and the tail `xs`. A list is constructed using empty list `[]` and `::`. For example, `[1, 2, 3]` actually is `1::2::3::[]`. – pad Oct 23 '12 at 18:14
  • Okay that makes sense, How can i get the function to return false if it is not true, because we used the "then" keyword to return the true cases. – cougar Oct 23 '12 at 18:18
  • Well, as I said in my answer, you missed a base case `fun in_list(element, []) = false | in_list(element, x::xs) = ...`. You simply return `false` if the input list is empty. – pad Oct 23 '12 at 18:23