[英]Pattern Matching a Haskell list of variable size
編輯 :我不應該在累了的時候編碼。 我正在編譯與運行時不同的程序副本。 很抱歉浪費您的時間。
我有以下代碼在程序啟動時使單個參數可選。
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 <- getArgs
行的模式匹配錯誤。
更准確地說,錯誤是: mbot: user error (Pattern match failure in do expression at core.hs:9:4-32)
檢查您的外殼是否沒有將以#
開頭的部分解釋為注釋,例如,在(shopt)上進行了interactive_comments
bash處理。 #somechannel
可以解釋為評論。
我認為,您的問題是由於兩種模式都使用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?"
這個例子對我有用,希望對你也一樣。)
無法復制:
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
我認為您的問題在別處。 也許您可以編寫出實際上符合並顯示出問題的最少代碼? 通常這是一個有益的練習。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.