Search code examples
haskellrecursionfoldreadabilitylcm

A more idiomatic way to write this Haskell LCM function


I'm just starting out with Haskell and hammered out this simple recursive algo to find the LCM for every number in a list. It works, but it's messy and I was hoping for some peer-review on how to make this more elegant, readable, and Haskell-y.

lcms list 
  | length list > 1 = lcms (lcm (head list) (head (tail list)):(tail (tail list)))
  | otherwise = list

So that takes a list and does LCM of the first two items, then prepends it to list minus those two elements. Basically, the psudocode I'm going for is like this:

lcms [a,b,c] = lcm (a, (lcm (b, c))

Any suggestions, anyone? I'm eager to improve at Haskell and write things that people can actually read. Efficiency tips are welcome too!

Thanks, all!


Solution

  • It's a fold:

    import Data.List
    
    lcms :: [Int] -> Int
    lcms xs = foldl' lcm 1 xs
    

    where lcm compute the lcm of just two numbers:

    lcm :: Int -> Int -> Int