Home > Blockchain >  Initializing variables inside conditional statements
Initializing variables inside conditional statements

Time:04-10

Why is it that whenever I initialize variables inside an if statement, for example, I always get a parse error on input 'let'?

case size of
    3 -> processHelper (tail queries) (writeDistanceInfo list temp) finalString
    2 -> 
        let from = head temp
        let to = head (tail temp)   -- Error is here

CodePudding user response:

There are at least two corrections that parse for me: attaching an in to each let or making the two let statements be part of a do block.

case size of
    2 ->
        let from = head temp in
        let to = head (tail temp) in
        ()

case size of
    2 -> do
        let from = head temp
        let to = head (tail temp)
        return ()

That said, using head and tail (and, usually, length, presumably used in the definition of size) is a code smell. Are you sure you didn't want this instead?

case temp of
    [from, to] -> ()

CodePudding user response:

The problem with your code is that you have two let statement. You are only entitled to one let .. in or one .. where clause. When you use let you can have multiple assignments:

test :: (Eq a, Num a) => a -> IO ()
test x = case x of
    2 -> print "2"
    3 ->
        let 
            y=1
            z=2
        in 
        print $ y z
  • Related