質問

I have been trying to get the last item in a list in Ocaml. This is what I tried.

let last2 (xs:'a list) : 'a =
    List.fold_left (fun acc element -> let acc=element) acc xs;; 

But it didn't work. My idea is that acc will be element till the last item in the list. And return acc after reaching the end of the list will give me the last item in the list.

Could someone help? Thanks in advance.

EDIT: I am getting close with the following

let last2 (xs:'a list) : 'a =
    List.fold_left (fun a b -> b) 1 xs;;

However, I can only use last2 on a integer list. A polymorphic last2 will be better.

役に立ちましたか?

解決

Your idea is correct, but your syntax for expressing it is wrong. This function:

# fun acc element -> let acc = element;;
Error: Syntax error

Isn't correct (as you've probably noticed).

To define a function that returns a value expr:

fun a b -> <expr>

Your expression should have the value b. So your function would look like this:

fun a b -> b

(With possible renamings.)

Another way to look at your problem is that when you use let as an expression, it needs an in. So you could write the function like this (though it's redundant):

fun a b -> let a = b in a

However, this form seems to be a result of thinking imperatively. You're not assigning a new value to a. You're just returning a value.

The following function is completely identical; it just renames the second a to something else:

fun a b -> let zzz = b in zzz

Generally speaking in OCaml you want to give up the idea of assigning values to variables. They are immutable and can't change value (generally speaking).

Update

Here's a session showing that fun a b -> b will solve the problem.

$ ocaml
        OCaml version 4.00.1

# List.fold_left (fun a b -> b) 0 [2; 3; 4; 88];;
- : int = 88

One thing that's easy to forget is that you need to supply a starting value for the accumulator. One obvious choice is the first element of the list. (There must be a first element; an empty list doesn't have a last element.)

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