1
votes

I'm programming binary arithmetic program using F#. I don't think my code was wrong but type error occurred.

Please examine my code and tell me what is wrong.

let carry a b c = if a then b||c else b&&c
let sum a b c = (if c then (a=b) else not (a=b))
let rec addc cin (l1:bool list) (l2:bool list) =
    if l2.Length>0 then sum(cin,l1.Head,l2.Head)::addc(carry cin,l1.Head,l2.Head), l1.Tail, l2.Tail) else l1

The error message:

if l2.Length>0 then sum(cin,l1.Head,l2.Head)::addc(carry(cin,l1.Head,l2.Head),l1.Tail,l2.Tail) else l1
--------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(173,51): error FS0001: This expression was expected to have type ('a * bool * bool -> bool -> bool) list but here has type bool list -> bool list -> ('a * bool * bool -> bool -> bool) list

2

2 Answers

3
votes

Your brackets and thus your syntax is incorrect and so the meaning of the parameters and the functions is not as intended (for example when calling the sum function you are calling it with one tuple parameter and not with three parameters). Adjusting the brackets corrects the problem and then the code compiles as expected:

let carry a b c = if a then b||c else b&&c
let sum a b c = (if c then (a=b) else not (a=b))
let rec addc cin (l1:bool list) (l2:bool list) = 
    if l2.Length > 0 then
        (sum cin l1.Head l2.Head) :: (addc (carry cin l1.Head l2.Head) l1.Tail l2.Tail)
    else
        l1 

val addc : cin:bool -> l1:bool list -> l2:bool list -> bool list

And a call to addc works as expected:

printfn "%A" (addc true [true;true;false] [false;false;false])

Have a look as this SO post - F# function calling syntax confusion - it explains functions, function calling and tuples in F#.

2
votes

Your functions 'carry' and 'sum' do not take tuples, so 'addc' can be rewritten to

let carry a b c = if a then b||c else b&&c
let sum   a b c = if c then a=b else not (a=b)
let rec addc cin (l1:bool list) (l2:bool list) =
    if l2.Length>0 
    then sum cin l1.Head l2.Head :: addc (carry cin l1.Head l2.Head) l1.Tail l2.Tail 
    else l1

Compiles to

val carry : a:bool -> b:bool -> c:bool -> bool
val sum : a:'a -> b:'a -> c:bool -> bool when 'a : equality
val addc : cin:bool -> l1:bool list -> l2:bool list -> bool list