Home > OS >  Count all the elements larger than x in a list
Count all the elements larger than x in a list

Time:10-23

I'm doing some exercise in "List" and "Match-With" but I'm a little stuck.

The exercise tell me Program the upper l x function that counts all the elements larger than x in the list

Example :

upper [10;20;30;40;50] 35; 

the results is 2.

I did this :

let rec upper x l1 =
  match l1 with
  |[] -> 0
  |[a] -> if (a>x) then 1 else 0
  |(a::r) when a>x ->  1 
  |(a::r) when a<x -> upper x r

but nothings work.

CodePudding user response:

Your solution looks pretty good, except this expression:

 1

doesn't make a lot of sense. It's just another way of writing the number 1. Clearly the answer isn't 1 in this case. For one thing, the answer depends on the count for the tail of the list r.

A problem for later is that a > x and a < x do not cover all the cases. In particular, they don't cover the case when a = x.

CodePudding user response:

let rec upper x l1 =
  match l1 with
  |[] -> 0
  |[a] -> if (a>x) then 1 else 0
  |(a::r) when a>x ->  1 
  |(a::r) when a<x -> upper x r

You've matched the empty list case, and when there is one or more elements in the list. The case where there is exactly one element is thus extraneous, as the tail of the list will be the empty list.

let rec upper x =
  function
  | [] -> 0
  | x'::xs when x' > x -> 1   upper x xs
  | _::xs -> upper x xs

For fun, this is readily solved with a fold.

let upper x lst = 
  List.fold_left (fun i x' -> if x' > x then i 1 else i) 0 lst
  • Related