I’m learning OCaml and am stuck with an exercise I’m trying to solve.
The exercise is to take an integer and output every even integer up to that integer like so:
Input: 5
Output: “0-2-4”
Input: 10
Output: “0-2-4-6-8”
I have to include errors for negative values, string inputs, stuff like that.
I was thinking of doing a recursive function and using pattern matching to set the edge cases and to stop the recursion.
My problem is, I’m coming from Ruby, and in Ruby my approach would be to simply make an array of integers up to the input, then modify that array with array.select, array.filter, etc., and concatenate the contents of the array into a string. I’m having much more difficulty doing something like this in OCaml.
Any tips?
You can use your Ruby approach in OCaml, and in fact it’s quite idiomatic to work this way. Instead of arrays you would probably want to use lists. I don’t know of a built-in function to get a list of integers up to a maximum, but it’s easy enough to write one. After that, you can use
List.filterto select the elements you want from the list.If you’re allowed to use extra libraries, there are many useful functions in OCaml Batteries Included. After a quick look at the
BatListmodule, I came up with this function for a range of integers less than n: