如何用Ruby和/或Haskell编写这个Clojure代码片段?

10

我正在开发一个Rails模板,尝试编写一些代码,使我能够填充一个表格或多个ul标签的多列。我想让它从上到下、从左到右地填充任意数量的列。由于我刚开始学习Ruby,所以无法解决这个问题。我也想知道如何用Haskell完成这个实用的代码片段。请提供对Clojure版本的改进建议:

(defn table [xs & {:keys [cols direction]
                   :or   {cols 1 direction 'right}}]
  (into []
        (condp = direction
          'down (let [c (count xs)
                      q (int (/ c cols))
                      n (if (> (mod c q) 0) (inc q) q)]
                  (apply map vector (partition n n (repeat nil) xs)))
          'right (map vec (partition cols cols (repeat nil) xs))))) 

使用这段代码后,我可以进行以下操作:

(table (range 10) :cols 3)

打印出来的结果应该如下所示:

0    1    2 
3    4    5 
6    7    8
9

还有一个更棘手的问题:

(table (range 10) :cols 3 :direction 'down)

看起来像这样:

0    4    8    
1    5    9    
2    6        
3    7        

你可能需要在Clojure版本中更改的三件事:
  1. 使用defnk(clojure.contrib.def),它更易于阅读。
  2. 使用关键字而不是符号。
  3. 不要使用两种不同的方法将其转换为向量,而是使用(vec(map vec(condp .....)))统一处理。
- nickik
6个回答

4

我不会阅读Clojure代码(我从未使用过这种语言),但根据示例,以下是我在Ruby中的实现方式。

def table array, cols, direction
   if direction==:down
      if array.size%cols != 0
         array[(array.size/cols+1)*cols-1]=nil
         #putting nil in the last space in the array
         #also fills all of the spaces before it
      end
      newarray=array.each_slice(array.size/cols).to_a
      table newarray.transpose.flatten(1), cols, :across
   elsif direction==:across
      array.each_slice(cols) do |row|
         puts row.join("  ")
      end
   else
      raise ArgumentError
   end
end

不错的解决方案。看到Ruby和Haskell在实际问题上的变化很酷。 - dnolen

4

如果我要用Haskell编写类似的代码,我会使用来自Hackage的Data.List.Split包:

import Data.List       (intercalate, transpose)
import Data.List.Split (splitEvery)

data Direction = Horizontal | Vertical deriving (Eq, Read, Show)

table :: Direction -> Int -> [a] -> [[a]]
table Horizontal cols xs = splitEvery cols xs
table Vertical   cols xs = let (q,r) = length xs `divMod` cols
                               q'    = if r == 0 then q else q+1
                           in transpose $ table Horizontal q' xs

showTable :: Show a => [[a]] -> String
showTable = intercalate "\n" . map (intercalate "\t" . map show)

main :: IO ()
main = mapM_ putStrLn [ showTable $ table Horizontal 3 [0..9]
                      , "---"
                      , showTable $ table Vertical   3 [0..9] ]

这些内容,比如Direction类型和transpose技巧,都是从jkramer的答案中得出的。在Haskell中,我不会像这样使用关键字参数(它实际上没有这种东西,但你可以像Edward Kmett的答案中那样使用记录来模拟它们),但我将这些参数放在第一位,因为它更适用于部分应用(defaultTable = table Horizontal 1)。splitEvery函数只是将列表分成适当大小的列表;其余代码应该很容易理解。 table函数返回一个列表的列表;要获得一个字符串,showTable函数插入制表符和换行符。(intercalate函数将列表的列表连接起来,用给定的列表分隔它们。它类似于Perl/Python/Ruby中的join,只不过是针对列表而不仅仅是字符串。)


2
切片和压缩可以给出一个简单的 Ruby 解决方案:
 def table(range, cols, direction=:right)
   if direction == :right
     range.each_slice cols
   else
     columns = range.each_slice((range.to_a.length - 1) / cols + 1).to_a
     columns[0].zip *columns[1..-1]
   end
 end


 puts table(0..9, 3, :down).map { |line| line.join ' ' }

2

这里是我用Haskell快速编写的一些东西。我确定它存在缺陷并且可以进行优化,但这是一个好的开始:

import System.IO
import Data.List

data Direction = Horizontal | Vertical

main = do
    putStrLn $ table [1..9] 3 Horizontal
    putStrLn "---"
    putStrLn $ table [1..9] 3 Vertical


table xs ncol direction =
    case direction of
        Horizontal -> format (rows strings ncol)
        Vertical -> format (columns strings ncol)
    where
        format = intercalate "\n" . map (intercalate " ")

        strings = map show xs

        rows xs ncol =
            if length xs > ncol
                then take ncol xs : rows (drop ncol xs) ncol
                else [xs]

        columns xs = transpose . rows xs

输出:

1 2 3
4 5 6
7 8 9
---
1 4 7
2 5 8
3 6 9

这对于垂直方向上非平方列数的情况并不能给出正确的答案;它打印的不是一个“_”乘以“ncol”的东西,而是一个“ncol”乘以“_”(其中“_”表示“任何必要的数字”)。总的来说,我认为它可以更加紧凑;请参考我的答案。 - Antal Spector-Zabusky
啊,我在找类似于splitEvery的东西,但是没有找到。 - jkramer

2

我的Ruby解决方案

def table(values)
  elements = values[:elements]
  cols = values[:cols]
  rows = (elements.count / cols.to_f).ceil

  erg = []

  rows.times do |i|
    cols.times do |j|
      erg << elements[values[:direction] == 'down' ? i+(rows*j) : j+i*(rows-1)]
      if erg.length == cols
        yield erg
        erg = []
      end        
    end
  end
  yield erg
end

使用和输出:

table(:elements => [0,1,2,3,4,5,6,7,8,9], :cols => 3) do |h,i,j|
  puts h.to_s << " " << i.to_s << " " << j.to_s
end

puts "---"

table(:elements => [0,1,2,3,4,5,6,7,8,9], :cols => 3, :direction => "down") do |h,i,j|
  puts h.to_s << " " << i.to_s << " " << j.to_s
end

0 1 2
3 4 5
6 7 8
9  
---
0 4 8
1 5 9
2 6 
3 7 

1
import Data.Array

stride :: Int -> Int -> Int
stride count cols = ceiling (fromIntegral count / fromIntegral cols)

type Direction = Int -> Int -> Int -> Int -> Int

right :: Direction
right count cols x y = y * cols + x

down :: Direction
down count cols x y = x * stride count cols + y

data Options = Options { cols :: Int, direction :: Direction }

options :: Options
options = Options 1 right

table :: Options -> [a] -> Array (Int,Int) (Maybe a)
table (Options cols dir) xs
    = listArray newRange (map f (range newRange))
    where count = length xs
          rows = stride count cols
          newRange = ((0,0),(rows-1,cols-1))
          f (y, x) 
              | ix < count = Just (xs !! ix)
              | otherwise = Nothing
              where ix = dir count cols x y

这为我们提供了一个相当通顺的近似于您原始查询的版本,包括可选参数:

*Main> table options { cols = 3 } [1..10]
listArray ((0,0),(3,2)) [Just 1, Just 2, Just 3
                        ,Just 4, Just 5, Just 6
                        ,Just 7, Just 8, Just 9
                        ,Just 10,Nothing,Nothing]

*Main> table options { direction = down, cols = 3 } [1..10]
listArray ((0,0),(3,2)) [Just 1,Just 5,Just 9
                        ,Just 2,Just 6,Just 10
                        ,Just 3,Just 7,Nothing
                        ,Just 4,Just 8,Nothing]

我将中间结果以数组形式留下,因为您曾表示计划将其格式化为表格或ul标签。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接