Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 594

Filtering an array in OCaml

$
0
0

I have an array of integers where I'm treating 0 in a special way. I need to manipulate the array so that the output is an array of the same size with all the zeros after all the non-zero values. For example:

input:  [| 10; 5; 4; 0; 6; 0; 0; 0; 0 |]output: [| 10; 5; 4; 6; 0; 0; 0; 0; 0 |]

This is some code I got to work:

let a = [| 10; 5; 4; 0; 6; 0; 0; 0; 0 |] inlet l = List.filter (fun c -> c <> 0) (Array.to_list a) inlet cells i = if i <= List.length l - 1 then List.nth l i else 0 inArray.init (Array.length a) cells;;

I have a feeling that this solution could be improved by addressing:

  1. converting back and forth between lists and arrays. Is there a better way than calling Array.to_list and then List.filter to keep the order and exclude certain values?
  2. accessing a list using List.nth which is O(i) for each position in the array. Is there a better way to use a list's values as the first source when populating an array?

Viewing all articles
Browse latest Browse all 594

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>