Koundinya Vajjha
Koundinya Vajjha

Reputation: 103

Recursive implementation of LCM in Haskell

I'm trying to write my own multiple LCM function in Haskell, one that computes the LCM of all the elements in a given list. I'm trying to use the property lcm(a,b,c) = lcm(a,lcm(b,c)) to make it recursive. Here is what I could come up with so far, but it is giving me errors which I'm not able to understand.

 multLCM xs 
    | length(xs) == 2 = lcm head(xs) last(xs)
    | length(xs) > 2 = lcm head(xs) multLCM(drop 1 xs)

Can someone help me improve this function so that it works?

Thanks a lot!

Upvotes: 0

Views: 433

Answers (2)

R B
R B

Reputation: 1107

Parentheses do not denote function application in Haskell. E.g., these are equivalent.

lcm head(xs) last(xs)
lcm head xs  last xs

That is, the function lcm provided the arguments head, xs, last, and xs.

Parentheses do allow you to specify function application by grouping a function with its arguments.

lcm (head xs) (last xs)

Upvotes: 2

ErikR
ErikR

Reputation: 52049

You should use pattern matching to deconstruct the list:

multiLCM (x:xs) = lcm x (multiLCM xs)
multiLCM [x]    = ???

Upvotes: 0

Related Questions