简体   繁体   中英

How to pass arguments to functions in haskell?

I'm trying to get files as arguments like this:

main = do  
 (file1:file2:file3:_) <- getArgs
 checkdata
 command <- getLine
 runQuery(words command)

The problem is this runQuery(words command) is not recognizing those arguments.

runQuery ("queryname":parameter1:parameter2) = do

 myfile1 <- readFile file1
 myfile2 <- readFile file2
 myfile3 <- readFile file3

The error I'm getting is:

Not in scope: file1
....

How can I pass them to functions like I intended to? Please help.

You have to pass file1 etc. to runQuery like every other function argument:

main = do  
 (file1:file2:file3:_) <- getArgs
 checkdata
 command <- getLine
 runQuery file1 file2 file3 (words command)

runQuery file1 file2 file3 ("queryname":parameter1:parameter2) = do
 ...

In Haskell, function arguments are separated simply by spaces, so if you had a function defined as

runQuery queryName param1 param2 = <implementation>

You would have a function of three arguments called runQuery with the arguments queryName , param1 , and param2 . You would then pass in arguments in the same syntax:

main = do
    (name:param1:_) <- getArgs
    param2 <- getLine
    runQuery name param1 param2

Here we are calling the function runQuery with the arguments name , param1 , and param2 , which were obtained from getArgs and getLine .

Note that the : character is an operator, it has nothing to do with function call syntax, and its purpose is the construct a new list by prepending an element to the front of an existing list. Since it is a constructor as well, it can be used for pattern matching, hence its use in (name:param1:_) <- getArgs . The _ is a wildcard pattern that matches anything, so it is taking the place of "the rest of the args passed in at the command line".

You seem to also be confused about scoping in Haskell. I would highly recommend you read some tutorials on beginning Haskell, my favorite is Learn You a Haskell For Great Good , to become more familiar with the basic syntax and language rules of the language before attempting more complicated programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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