【问题标题】:Pattern Matching a Haskell list of variable size模式匹配可变大小的 Haskell 列表
【发布时间】:2011-04-20 13:05:22
【问题描述】:

编辑:我不应该在这么累的时候编码。我正在编译与正在运行的程序不同的副本。很抱歉浪费了您的时间。

我有以下代码可以在我的程序启动时将单个参数设为可选。

main = do
    args <- getArgs
    handleArgs args

handleArgs :: [String] -> IO ()
handleArgs (server:nick:channel:[]) = IRC.startIRC server 6667 nick channel
handleArgs (server:port:nick:channel:[]) = IRC.startIRC server (read port :: Int) nick    channel
handleArgs _ = putStrLn "Incorrect arguments given."

如果我像./program irc.freenode.net 6667 somenick #somechannel 一样运行它,它就会运行。但是,如果我像 ./program irc.freenode.net somenick #somechannel 一样运行它,如果我理解正确的话,这应该使 args 成为列表 "irc.freenode.net":"somenick":"#somechannel":[], 当我在使用 ghc 编译后尝试运行它时,它会给出指向 args &lt;- getArgs 行的模式匹配错误。

更准确地说,错误是: mbot: user error (Pattern match failure in do expression at core.hs:9:4-32)

【问题讨论】:

  • 顺便说一句:main 函数最好写成getArgs &gt;&gt;= handleArgs

标签: haskell pattern-matching


【解决方案1】:

检查您的 shell 是否没有将以 # 开头的部分解释为注释,例如在(shopt)上使用interactive_comments bash。 #somechannel 可能被解释为评论。

【讨论】:

  • 我和 bash 就是这种情况——他需要转义 #.
【解决方案2】:

我认为,您的问题来自两种模式中 xs 的使用, 什么时候适合匹配 []

foobar :: [String] -> String
foobar (a:b:[]) = b         -- matches on exactly two items
foobar (a:b:c:[]) = c -- matches on exactly three items
foobar _ = "hurz?"

这个例子对我有用,也应该对你有用。)

  • 问题是,与 xs 的匹配匹配空列表以及任何其他剩余的尾部。

【讨论】:

  • 不幸的是,不幸的是,更新了问题中的代码,因为您的方式确实更有意义。
  • 不,他的原始版本很好 - 问题出在他没有展示的东西上。
  • 我明白了.. 我现在无法重现该问题,抱歉
【解决方案3】:

无法重现:

import System.Environment (getArgs)
main = do
    args <- getArgs
    handleArgs args

handleArgs :: [String] -> IO ()
handleArgs (server:port:nick:channel:xs) = print 4
handleArgs (server:nick:channel:xs) = print 3

输出:

$ ghc --make match.hs
[1 of 1] Compiling Main             ( match.hs, match.o )
Linking match ...
$ ./match
match: match.hs:(7,0)-(8,44): Non-exhaustive patterns in function handleArgs

$ ./match a b c
3
$ ./match a b c d
4
$ ghc -V
The Glorious Glasgow Haskell Compilation System, version 6.12.1

我认为你的问题在其他地方。也许您可以编写一段真正符合并展示问题的最小代码?这通常是一个信息丰富的练习。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多