views:

350

answers:

2

Im new to Haskell!! I wrote this code:

import Data.List
inputIndex :: [String] -> [String] -> Bool
inputIndex listx input = and [x `elem` listx |x <- input]
inputIndex = if inputIndex == true
          then putStrLn ("ok")

It works fine without the if statement but when I put the if statement the following error is shown:

Syntax error in expression (unexpected `}', possibly due to bad layout)

What am I doing wrong here?

Thanks

+9  A: 

A couple of things are wrong here:

  • You will need an else clause.
  • True must be capitalized.
  • inputIndex must always take two arguments (right now it does not, in the last case).

I guess you want something like this...

inputIndex :: [String] -> [String] -> IO ()
inputIndex listx input = if inputIndex' listx input
                             then putStrLn ("ok")
                             else putStrLn ("not ok")
  where
    inputIndex' :: [String] -> [String] -> Bool
    inputIndex' listx input = and [x `elem` listx |x <- input]

(Here I defined a new function with a near-identical name, by appending a prime/apostrophe. By defining it in the where clause, it is only visible to the outer inputIndex function. You can call this a helper-function, if you will. I could also have chosen a completely different name, but I'm uncreative.)

You could also condense this to the following (which is also more general):

allPresent :: (Eq t) => [t] -> [t] -> IO ()
allPresent xs ys = putStrLn (if and [y `elem` xs | y <- ys] then "ok" else "not ok")
Stephan202
thanks! it worked as intended. could you pls tell me the meaning of the comma in front of inputIndex .
pier
it worked even without the 1st lineinputIndex :: [String] -> [String] -> IO ()
pier
@dlna: the comma is an apostrophe. I updated my answer with some explanation. The first line is indeed unnecessary. Without it, the function works for every pair of lists of the same type (because Haskell then infers the most general type possible.)
Stephan202
@dlna You really need to sit down with a Haskell book and figure out what each line of that code actually does, if you have to comment on a function working without it's type definition.
Ed Woodcock
A: 
  1. It's "True", not "true".
  2. Your second inputIndex implementation is not compatible with the first one. All your pattern cases for a function must have the same signature ([String] -> [String] -> Bool)
  3. The error you show here is not generated by this code, because there is no '}' here.
  4. putStrLn has signature String -> IO() while your inputIndex looks like it's supposed to be pure - just return the value and print it somewhere else.
viraptor