Hi everyone, I’m trying to define the lcm of a list of numbers. This is what I did:
lcmm :: (Integral a) => a -> Int
lcmm []=0
lcmm [x]=x
lcmm [a,b] = lcm a b
lcm (x:xs = lcmm (x) (lcmm xs)
I don’t know why this is not working
Hi everyone, I’m trying to define the lcm of a list of numbers. This is what I did:
lcmm :: (Integral a) => a -> Int
lcmm []=0
lcmm [x]=x
lcmm [a,b] = lcm a b
lcm (x:xs = lcmm (x) (lcmm xs)
I don’t know why this is not working
A missing parenthesis, missing character and one character too many:
lcmm (x:xs) = lcm (x) (lcmm xs)
But that is not all. The type of your function lcmm :: (Integral a) => a -> Int
seems to indicate that it takes an argument of type Integral a => a
. But in the definition you use list patterns. You can’t know that your input is going to be a list if you use the general type Integral a => a -> Int
(in fact lists are not members of the Integral class), so you can’t use things like []
, [x]
or (x:xs)
in the pattern match.
A way to solve this would be to change the type of your function:
lcmm :: [Int] -> Int
On the mathematical side, I would define lcmm [] = 1
. Because the identity of multiplication is 1. That allows you to write the function as a nice fold: lcmm = foldr lcm 1
.
If you really want to take a list of elements of type Integral a => a
as input I would recommend writing it like this:
lcmm :: Integral a => [a] -> a
lcmm [] = 1
lcmm (x:xs) = lcm x (lcmm xs)