I am trying to define a function that computes for any positive integer the square of its factorial
(I am a beginner in Haskell any tips or help is appreciated)
I have tried a couple different ways one i believe to work and one definition i don't understand why it doesn't work
Function i believe works:
squarefact:: Int -> Int
squarefact 0 = 1
squarefact n = n * n * squarefact(n-1)
Function I don't understand why it doesn't work:
squarefact:: Int -> Int
squarefact 0 = 1
squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )
An explanation and walk through of the dunctions defined would help me understand them better thanks.
The equation
squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )
could be rewritten in mathematical notation as
(n!)^2 = n * ((n-1)!)^2 * n * ((n-1)!)^2
but this identity is incorrect. The right hand side includes factors 1,2,....,n-1
four times instead of only two, as in the left hand side.
By comparison,
squarefact n = n * n * squarefact(n-1)
is correct, since on both sides all the factors occur exactly twice.
A factorial function can be defined in Haskell as
factorial n = product [1..n]
(where product
is a function that calculates the product of all the numbers in a given list.)
Hence,
squarefact n = square (factorial n) =
= square (product [1..n])
= product [1..n] * product [1..n]
= 1 * 2 * 3 * ... * (n-1) * n *
1 * 2 * 3 * ... * (n-1) * n
= product [1..(n-1)] * n * product [1..(n-1)] * n
= n * n * square (product [1..(n-1)])
= n * n * squarefact (n-1)
The equality re-writes break down for n=0
( squarefact 0 /= 0 * 0 * squarefact (-1)
), so it must be handled as a special case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With