简体   繁体   中英

Is it possible to uses guards within guards?

I wonder if it is possible to use guards inside guards in haskell. like this :

analyser modele instr
  |  instr == NoCom  = (modele, "No command" ,[])
  |  instr == ComK   | (read comargstr1) == 0 = function1 modele Nothing
                     | (read comargstr1) == 1 = function1 modele (Just (read comargstr1))
                     | (read comargstr1) <  0 = function1 modele (Just (read comargstr2))
                     | otherwise              = function2 modele
  | othercases...
  | othercases...

In my example, i can't evaluate (read comargstr1) in the first column of guards at all because comargstr1 doesn't always return a compatible string readable with read (fatal error)

I didn't managed to use guards within guards!

Is it possible to do it (Is there a trick, an option, something special, ...) or is it purely impossible?

Thank you in advance for your Help!

Layout doesn't apply to guards, so it doesn't matter how you align them.

The closest you can do is to use MultiWayIf for the second-level guards.

You can achieve something vaguely similar as follows:

analyser modele instr
  |  instr == NoCom = (modele, "No command" ,[])
  |  instr == ComK  = foo
  | othercases...
  | othercases...
  where foo | (read comargstr1) == 0 = function1 modele Nothing
            | (read comargstr1) == 1 = function1 modele (Just (read comargstr1))
            | (read comargstr1) <  0 = function1 modele (Just (read comargstr2))
            | otherwise              = function2 modele

Note that you will need a distinct name foo for every branch. Also, if a nested guard list does not end with otherwise (or equivalent) then control will not be transfered to the next guard in the topmost level.

Just either repeat both conditions, or use an if after a single guard. Two/nested guards aren't supported as far as I'm aware.

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