惯用的Haskell用于将矢量转换为2D矩阵?

时间:2017-12-16 19:19:41

标签: haskell

我有一个整数向量,我想将其转换为二维矩阵。保证输入可以被行大小整除。在Haskell中最常用的方法是什么?

在Python中我会这样做:

# Taken from itertools docs.
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

m = list(grouper(v, n))

1 个答案:

答案 0 :(得分:1)

假设你的意思是转向&#34;向量&#34;将Haskell列表表示为&#34;矩阵&#34;表示为列表列表,然后一个惯用的解决方案可能会使用<li data-time="3:07">Flexbox Video</li> <li data-time="5:59">Redux Video</li>来中断每一行,使用简单的模式匹配和递归构建行 EITHER 的列表:

splitAt

可能有一个警卫,以避免令人尴尬的无休止的循环:

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs =
  let (row, rest) = splitAt n xs
  in  row : chunksOf n rest

OR ELSE 使用chunksOf :: Int -> [a] -> [[a]] chunksOf n | n > 0 = chunks where chunks [] = [] chunks xs = let (row, rest) = splitAt n xs in row : chunks rest

unfoldr

如果长度不是行长度的倍数,则最后一行将比其余行短。要允许最后一个不完整行的填充字符,您可以写:

import Data.List
chunksOf :: Int -> [a] -> [[a]]
chunksOf n | n > 0 = unfoldr chunk
  where
    chunk [] = Nothing
    chunk xs = Just (splitAt n xs)

正如@Will Ness在评论中指出的那样,import Data.List chunksOfWithFill :: Int -> a -> [a] -> [[a]] chunksOfWithFill n filler | n > 0 = unfoldr chunk where chunk xs = case splitAt n xs of ([],[]) -> Nothing (xs,[]) -> Just (fill xs, []) result -> Just result fill xs = take n (xs ++ repeat filler) 包的chunksOf模块中已经提供了Data.List.Split

相关问题