keivn
keivn

Reputation: 114

ocaml putting a integer into a list

I a noobie with ocaml, my problems is how get the digit of an integer in the ocaml and how to put them into a list by recursive calls

OCaml function digits : int -> int list that takes an integer n as an argument and if the integer is positive, returns the list of digits of n in the order in which they appear in n ie:

# digits 3124;;
- : int list = [3;1;2;4] 


# let rec digits n =
  if n >0 then digits(n/10)::[]
  else [];;

Upvotes: 2

Views: 6081

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

For learning purposes, it might be useful to finish OP's original code rather than switching to using an accumulator. The key thing missing is that it doesn't combine the current digit (n mod 10) with the value returned by the recursive call.

As lbonn says, if you had a lot of numbers to convert you would rewrite to avoid repeatedly appending to a list (which takes quadratic time and generates a lot of temporary data).

Upvotes: 2

lbonn
lbonn

Reputation: 2599

If you write digits directly as a recursive function, you'll find it hard to print the digits in the correct order without reversing the whole list at the end or appending elements to the end of the current list (both unefficient approaches).

This is best done with an intermediate terminal recursive function:

let digits2 d =
    let rec dig acc d =
        if d < 10 then d::acc
        else dig ((d mod 10)::acc) (d/10) in
    dig [] d
;;

Here, dig takes an accumulator which is used to build the list and is passed on the next recursive call and returned as a whole at the end (except for the cons of d here). This is a pretty common pattern when writing terminal recursive functions.

It may take a little time to get used to this style of writing, but eventually it will come. Trying to rewrite simple functions like this one is in my view a good way to train yourself.

Upvotes: 4

Related Questions