通过哈姆雷特中的分隔符分隔输出列表元素

时间:2015-08-07 06:55:24

标签: haskell hamlet shakespeare-text

如果我有下面的代码,如何删除输出中的最后一个逗号?有没有办法看到我在循环中的位置以及我是否在最后?

{-# LANGUAGE QuasiQuotes #-}

import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Hamlet (hamlet)

main = do
  let xs = [1 :: Int, 2, 3]
  putStrLn $ renderHtml $ [hamlet|
                              $forall x <- xs
                                $if x == 1
                                  ONE,
                                $else
                                  #{x},
                              |] ()

这会产生ONE,2,3,,我需要ONE,2,3。对于任何任意列表的课程。请帮忙。

2 个答案:

答案 0 :(得分:2)

我认为你必须在Haskell方面实现这种逻辑,例如:

import Data.List (intercalate)

main = do
  let xs = [1 :: Int, 2, 3 ]
      str = intercalate "," $ map fmt xs
      fmt 1 = "ONE"
      fmt x = show x

  ... [hamlet| #{str}] ...

一些以特殊方式处理序列的第一个或最后一个元素的视觉效果也可以使用CSS实现,即使用<ul><li>标记。

答案 1 :(得分:1)

您可以使用intersperse功能:

{-# LANGUAGE QuasiQuotes #-}

import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Hamlet (hamlet)
import Data.List (intersperse)

main = do
  let xs = intersperse "," $ map show [1 :: Int, 2, 3]
  putStrLn $ renderHtml $ [hamlet|
                              $forall x <- xs
                                $if x == "1"
                                  ONE
                                $else
                                  #{x}
                              |] ()

这会产生这个:

ONE,2,3

请注意,intersperse会在您的列表中插入中间,。因此,在hamlet quasiquoter中,您只需显示列表:

λ> intersperse "," $ map show [1,2,3]
["1",",","2",",","3"]