列表中的最后一个元素使用ocaml List.fold_left [英] last element in list using ocaml List.fold_left

查看:545
本文介绍了列表中的最后一个元素使用ocaml List.fold_left的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  let last(xs:'a list) :'a = 
让rec aux xs prev =

|匹配xs [] - > prev
| x :: ys - >
中的aux ys x与
|匹配xs [] - >失败没有元素
| x :: xs - > aux xs x

如何使用 OCaml中的List.fold_left 函数?
提前致谢!

解决方案

fold_left 从头部到尾部,因此传递给 fold_left 的函数应该只将累加器替换为列表的当前元素。因此,简单地说,

  let last = function 
| x :: xs - > List.fold_left(fun_y - > y)x xs
| [] - > failwithno element

您可以直接编写函数,不需要 aux

  let rec last = function 
| x :: [] - > x
| _ :: xs - >最后xs
| [] - > failwithno element


I can find the last element of a list by the following code.

let last (xs:'a list) : 'a =
    let rec aux xs prev =
        match xs with
        | [] -> prev
        | x::ys -> aux ys x in
    match xs with
    | [] -> failwith "no element"
    | x::xs -> aux xs x

How do I find the last element of the same list using the List.fold_left function in OCaml? Thanks in advance!

解决方案

fold_left accesses the list from the head to the tail, thus the function passed to fold_left should just replace the accumulator with the current element of the list. Thus simply,

let last = function
  | x::xs -> List.fold_left (fun _ y -> y) x xs
  | []    -> failwith "no element"

You can write your function directly, without the aux function.

let rec last = function
  | x::[] -> x
  | _::xs -> last xs
  | []    -> failwith "no element"

这篇关于列表中的最后一个元素使用ocaml List.fold_left的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆