【问题标题】:Haskell: define list over multiple linesHaskell:定义多行列表
【发布时间】:2011-11-03 22:17:36
【问题描述】:

我正在定义一个 TestList (HUnit),并希望将定义分布在多行中。我得出以下解决方案:

tests = TestList ([TestLabel "test1" test1] ++
                  [TestLabel "test2" test2] ++
                  [TestLabel "test3" test3] ++
                  [TestLabel "test4" test4] ++
                  [TestLabel "test5" test5])
  • 使用++ 运算符是否是执行此类操作的正确方法?
  • 有没有更好或更优雅的方法来做到这一点?

【问题讨论】:

标签: haskell


【解决方案1】:

我会写

tests = TestList
    [ TestLabel "test1" test1
    , TestLabel "test2" test2
    , TestLabel "test3" test3
    , TestLabel "test4" test4
    , TestLabel "test5" test5 ]

【讨论】:

  • 令人着迷!在他的自然栖息地的哈斯克尔!请注意他的 Haskellisms:野生 Haskellers 将逗号与左括号对齐是很常见的。由于 Haskell 的空格很重要,因此在开始列表定义或类似内容时,野生 Haskell 也很常见转到下一行。克里基!
【解决方案2】:

@ephemient 变体仍有改进的地方:根本不要使用TestLabel,使用~: 快​​捷方式:

tests = TestList
    [ "test1" ~: test1
    , "test2" ~: test2
    , "test3" ~: test3
    , "test4" ~: test4
    , "test5" ~: test5 ]

请注意,构造断言的运算符更多:@?@=?@?=。有关详细信息,请参阅 http://hunit.sourceforge.net/HUnit-1.0/Guide.htmlhttp://hackage.haskell.org/package/HUnit。快捷方式巧妙地使用优先级和类型类,因此您将获得更少的括号噪音,但代价是稍微更糟的错误消息。

【讨论】:

    【解决方案3】:

    也许我遗漏了一些东西,但为什么不只是逗号?这似乎与普通列表并没有什么特别的不同。

    tests = TestList ([TestLabel "test1" test1,
                       TestLabel "test2" test2,
                       TestLabel "test3" test3,
                       TestLabel "test4" test4,
                       TestLabel "test5" test5])
    

    【讨论】:

    • 因为太明显了... :( 我有错字所以我猜这由于某种原因不起作用...
    • Scolytus:你很可能在缩进方面犯了错误。 Haskell 特有的重要空白需要一点时间来适应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多