I have a list
let derp = [1; 2; 3; 4; 5];;
Im such a beginner in this language that this may seem stupid, but if I wanted just the middle value (3), how would I return that?
如果您不介意使用List模块,那么可以这样做:
List.nth derp (List.length derp / 2);;
There are many ways to do this. You said, in your comments that there will always be 5 elements in this list.
First, you can use Pavel solution : List.nth derp (List.length derp / 2);
. If you want to put it in a function, let middle list = List.nth list(List.length derp / 2);
The 2nd solution is to use pattern matching :
let middle list = match list with | [] -> 0 | p :: q :: r :: s :: t -> r
Note that here, I assume that the list is a list of Int
The 3rd is a rewritten version of the first 1 solution, but here I suppose that you know the lenght of the list :
let rec middle list n = if(n == 0) if(list.isEmpty) failwith "Empty List" else list.head else middle list (n - 1)
exception Error
let rec middle = function
[] -> raise Error
| [x] -> x
| x::tl -> middle (List.tl (List.rev tl))
Test :
# middle [1];;
- : int = 1
# middle [1;2];;
Exception: Error.
# middle [1;2;3];;
- : int = 2
# middle [1;2;3;4;5];;
- : int = 3
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.