views:

79

answers:

1

I am trying to convert a given decimal value its corresponding binary form. I am using Ocaml about which I don't know much and am quite confused. So far I have the following code

let dec_to_bin_helper function 1->'T' | 0->'F'
let dec_to_bin x = 
           List.fold_left(fun a z -> z mod 2 dec_to_bin_helper a) [] a ;;

I must include here that I want my output to be in the form of a list of T's and F's where T's represent the binary 1's and F's represent binary 0's If I try to run the above code it gives me an error saying "Error: This expression is not a function; it cannot be applied" I understand that the part where I am calling the helper function is wrong... Any help in the matter would be appreciated!

+2  A: 

I don't really understand your second function at all. You are folding an empty list, and your function takes an argument x which it never uses. Am I correct in assuming that you want to take a number and return a list of 'T's and 'F's which represent the binary? If that is the case, this code should work:

let dec_to_bin x =
      let rec d2b y lst = match y with 0 -> lst
        | _ -> d2b (y/2) ((dec_to_bin_helper (y mod 2))::lst)
      in
      d2b x [];;

This function inserts (x mod 2) converted into a T/F into a list, then recursively calls the function on x/2 and the list. When x = 0 the list is returned. If call it on 0 an empty list will be returned (I'm not sure if that's what you want or not).

I think the problem that you had is that you are treating lists as if they are mutable and thinking that fold mutates the list. That is not the case, fold just goes through each element in a list and applies a function to it. Since your list is empty it didn't do anything.

Niki Yoshiuchi
Niki, this was precisely what I wanted to do and I now understand how I used fold_left wrongly. Thanks for explaining! But just to make things more clear do you mind explaining how your nest function "let rec d2b x lst = (* code *) in d2b x [];;" works? In particular if I were to trace this by hand how would "in d2b x [];;" work?
Max Eastman
Ah, sure. d2b is a nested function. let rec d2b x = (* code *) in just declares the function, the following code calls it on x (I probably shouldn't have reused the same variable name, I'm going to edit that) and an empty list. The reason I chose to do this is so that you call dec_to_bin # and don't have to worry about the list.
Niki Yoshiuchi
This makes lot of sense now. Thanks again! If I understand it right then it means that "x" from "dec_to_bin" is passed into "d2d" as "y" and then as "d2b" calls itself "y" gets modified and as a result we get our list? Sorry if I am asking too many questions, I just want to get the basics right! Thanks a lot for your help!
Max Eastman
That's exactly correct. Although I wouldn't say that "y" gets "modified" it's just recursively called with a different value.
Niki Yoshiuchi