简体   繁体   English

do块中的case表达式的Haskell语法

[英]Haskell syntax for a case expression in a do block

I can't quite figure out this syntax problem with a case expression in a do block. 我无法用do块中的case表达式来解决这个语法问题。

What is the correct syntax? 什么是正确的语法?

If you could correct my example and explain it that would be the best. 如果你能纠正我的例子并解释它是最好的。

module Main where 

main = do   
     putStrLn "This is a test"
     s <- foo
     putStrLn s  

foo = do
    args <- getArgs 
    return case args of
                [] -> "No Args"
                [s]-> "Some Args"

A little update. 一点点更新。 My source file was a mix of spaces and tabs and it was causing all kinds of problems. 我的源文件是空格和制表符的混合,它引起了各种各样的问题。 Just a tip for any one else starting in Haskell. 对于从Haskell开始的任何其他人来说,只是一个提示。 If you are having problems check for tabs and spaces in your source code. 如果您遇到问题,请检查源代码中的选项卡和空格。

return is an (overloaded) function, and it's not expecting its first argument to be a keyword. return是一个(重载)函数,并不期望它的第一个参数是关键字。 You can either parenthesize: 您可以使用括号:

module Main where 
import System(getArgs)

main = do   
     putStrLn "This is a test"
     s <- foo
     putStrLn s  

foo = do
    args <- getArgs 
    return (case args of
                [] -> "No Args"
                [s]-> "Some Args")

or use the handy application operator ($): 或使用方便的应用程序运算符($):

foo = do
    args <- getArgs 
    return $ case args of
                [] -> "No Args"
                [s]-> "Some Args"

Stylewise, I'd break it out into another function: Stylewise,我将其分解为另一个函数:

foo = do
    args <- getArgs 
    return (has_args args)

has_args [] = "No Args"
has_args _  = "Some Args"

but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence. 但你仍然需要括号或使用($),因为return接受一个参数,而函数应用程序是最高优先级。

Equivalently: 等价的:

foo = do
  args <- getArgs 
  case args of
        [] -> return "No Args"
        [s]-> return "Some Args"

It's probably preferable to do as wnoise suggests, but this might help someone understand a bit better. 这可能比wnoise建议的更好,但这可能有助于人们更好地理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM