简体   繁体   中英

How do I create a function which reverses an int list in OCaml?

I have a type intlist:

type intlist = Nil | Cons of int * intlist

and I'd now like to write a function that reverses the list. I have no real idea how to go about this. in class, our prof defined a function within a function, I believe, but I don't have the solution with me. How would one do this, simply? I would appreciate if we can keep the coding rather rudimentary, seeing as I'm relatively new to this.

So far, I only have

let reverse (l:intlist):intlist = 
match l with
Nil -> Nil
|Cons(a, Nil) -> Cons(a,Nil)

This is how I tend to create these kinds of functions, so I've written the trivial part (which granted, may not actually be what I need to start with). Any help is appreciated, thanks!

You indeed need a helper function, since for the reversing you need to build another list, so you need a function that will recurse into one list, while building another list, ie, that has two arguments. In fact, this helper function is called rev_append and it is appending a reversed contents of one list to another. But let's try to make it using a helper function defined in the scope of the rev function:

 let rev xs =
   let rec loop xs ys = match xs with
     | Nil -> ys
     | Cons (x,xs) -> loop xs (Cons (x,ys)) in
   loop xs Nil

So, to reverse a list we just take each element of a list and put it into another list. Since list behaves like a stack we are getting the reversed list for free. It is like Hanoi towers, when you pick elements from one list (tower) and put them to another, they will end up in a reversed order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM