0

I am trying to write a function called check that when applied to n returns a Bool indicating whether the ∑r=0 to n (n choose r) = 2^n

I have made the factorial and choose functions which work but I am having difficulty understanding what the type would be for the check function. I have written what I have done for it and I think logically it might work but I am not sure. The error I get when running says 'couldn't match type a -> Bool to actual type Bool' but I am not entirely sure how to make it an actual Bool type.

factorial :: (Integral a) => a -> a
factorial 0 = 1 
factorial n = n * factorial (n - 1)

choose :: (Integral a) => a -> a -> a
n `choose` r
    | r < 0     = 0
    | r > n     = 0
    | otherwise = factorial n `div` (factorial r * factorial (n-r))

check :: (Integral a) => a -> a -> Bool 
check n = (if (factorial (choose n)) == 2^n then True else False)
3
  • 1
    1) Fix the type: a->a->Bool takes two arguments, but you only need one. 2) Try a list comprehension e.g. sum [ ... | r<-[0..n] ] == 2^n. 3) Never use if condition then True else False -- it's equivalent to just condition, only more complex to read. Commented Oct 17, 2022 at 12:49
  • 2
    Style note: if (factorial (choose n)) == 2^n then True else False is equivalent to just writing: factorial (choose n) == 2^n Commented Oct 17, 2022 at 18:25
  • 1
    Some observations. choose takes two arguments, but you have given it only one in factorial (choose n); perhaps this is related to the problem you are having. Where is the code reflection in check of r, and its bounds of 0 to n, and the summation of the results? What math is being reflected by the factorial in check? Commented Oct 18, 2022 at 1:39

1 Answer 1

2

The correct type declaration for check is a -> Bool

The types are separated by -> and grouped using parentheses.

The last type is the returned type, here Bool.

The previous types are the input types, here a.

Your error message is couldn't match type a -> Bool to actual type Bool. What's happening here is that Haskell matches the a to variable n, but is then left with a -> Bool, when actually the return type is Bool.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.