質問

I found this member function on the Internet which uses foldl

fun memeber3 (x,xs)=
              foldl (fn (y,b)=>b orelse x=y) false;

but when I run it with an element and a list it does not work, instead of true or false it reacts like I am writing a new function and prints something like this :

fn int list ->bool

Can someone explain to me how the above function finds if an element belongs to a list and how to execute it properly?

役に立ちましたか?

解決

I think the function should have been declared as:

fun memeber3 (x,xs)= foldl (fn (y,b)=>b orelse x=y) false xs

Notice the use of xs at the end, in whose case you could use it by doing

val x = memeber3(1,[1,2,3])

Or it could have been declared as

fun memeber3 x = foldl (fn (y,b)=>b orelse x=y) false

In this case using currying: notice the lack of parenthesis for the arguments and the lack of an argument xs. This is so because both member3 and fold expect a list as their last argument, and so we can avoid declaring it. This way, member3 actually produces a new function expecting a list xs.

And you could have used it like this:

val x = memeber3 1 [1,2,3]

Notice the invocation without the use of parenthesis. This is a curried invocation.

It may be worth saying that the problem of using fold here is that you will have to go over the entire list, even if you find the element you were looking for in the first iteration. That is suboptimal solution.

I think it would be preferable to avoid doing more computations once you have found what you were looking for. Somewhat like:

fun exists(e, xs) =
    case xs of
         [] => false
       | x::xs' => x = e orelse exists(e, xs')

The short-circuiting nature of the orelse operator here would avoid invoking another iteration of exists if the element is found.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top