0

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!

R B
  • 1,109
  • 9
  • 13

2 Answers2

2

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)
R B
  • 1,109
  • 9
  • 13
  • Can you please let me know when I can use `$` and `.` in place of parentheses? I always found that confusing – Koundinya Vajjha Jul 28 '16 at 18:26
  • @KoundinyaVajjha Have you seen [this answer](http://stackoverflow.com/questions/940382/haskell-difference-between-dot-and-dollar-sign#1290727)? – R B Jul 28 '16 at 18:43
0

You should use pattern matching to deconstruct the list:

multiLCM (x:xs) = lcm x (multiLCM xs)
multiLCM [x]    = ???
ErikR
  • 51,541
  • 9
  • 73
  • 124
  • I'm not sure how to complete your answer. I don't want my `multiLCM` to be defined for single element lists and want it to be just the usual `lcm` for two element lists. Can pattern matching be done in this case? Something like `x:y:xs` maybe? – Koundinya Vajjha Jul 28 '16 at 18:29
  • 1
    Why? I can't think of any good reason not to define multiLCM for a single element list. – ErikR Jul 28 '16 at 18:34