I'd like to implement a function that has the following characteristics:
- take an
array
(Array[A]
) and a number ofpieces
to return (Int
) as parameters - returns the
array
array split inpieces
pieces. - all pieces should be of equal length if possible, else the first ones should be one element longer to the last ones (if the length of
array
isn't a multiple ofpieces
)
in Haskell I would have coded something along those lines:
split :: [a] -> Int -> [[a]]
split list pieces = go list (length list `div` pieces)
where
go xs n | l > n && m == 0 = take n xs : go (drop n xs) n
| l > n = take (n + 1) xs : go (drop (n + 1) xs) n
| otherwise = [xs]
where
l = length xs
m = l `mod` n
Though in Scala I encounter many difficulties to code this (basic) function. For the recursion first, Array
doesn't seem that adapted. Then, the if
structure that'd allow me to implement the kind of guards I'm using in haskell aren't allowed in place of an expression, which seems weird to me. Another problem I have is that I wouldn't know how to make my scala code polymorphic (as my Haskell code is). Last but not least, I don't get how I'd go about making not only the a
equivalent polymorphic, but also the Array
instance, because there are many basic collections in Scala.
I'd be fine with either a complete explained solution or simple hints to answer my misunderstandings.