1

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

{-# 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。当然,对于任何任意列表。请帮忙。

4

2 回答 2

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 来实现,即使用 a<ul><li>标签。

于 2015-08-07T07:33:12.933 回答
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"]
于 2015-08-07T07:33:35.240 回答