嵌套在haskell中

时间:2009-05-17 08:42:48

标签: haskell nested-if

//编辑5 当我只使用这两行时

  index :: [String] -> [String] -> Bool
  index a b = and [x `elem` a |x <- b]

它工作正常!!!!

例如:

index [“asd”,“asdd”,“露水”] [“asdd”,“asdad”]

但是当我使用下面提到的整个代码时

empty [] = True
empty _ = False

    index a b = do
             if empty a
              then do putStrLn "a is empty"
                      else return ()
             if empty b
              then do putStrLn "b is empty"
                      else return ()
        where
          index :: [String] -> [String] -> Bool
          index a b = and [x `elem` a |x <- b]

没有输出!这就是我得到的问题!!

//编辑6

index a b = do index'
         if empty a
          then do putStrLn "a is empty"
                  else return ()
         if empty b
          then do putStrLn "b is empty"
                  else return ()
    where
      index' :: [String] -> [String] -> Bool
      index' a b = and [x `elem` a |x <- b]

感谢

4 个答案:

答案 0 :(得分:4)

这有点偏离主题,因为您可能正在尝试学习布局规则以及如何嵌套ifs,但是您在修订版6中显示的代码只是使用if来执行错误检查。我只是通过模式匹配而不是if进行错误检查。

index [] _ = putStrLn "a is empty"
index _ [] = putStrLn "b is empty"
index a b = putStrLn (show index')
    where index' = and [x `elem` a | x <- b]

return ()之后您不需要putStrLn,因为它已经为您返回()。)

模式匹配更容易正确,因为它不需要大量的缩进等。


编辑:

我稍微改变了index'的定义。在我的版本中,它是局部变量而不是本地函数。在Haskell中,没有太大区别,只是index'使用来自周围a函数的bindex,因此它不需要参数。 (诚​​然,index'对变量来说不是一个好名字。)

我也没有留下类型注释,因为我通常不会写它们。但是当某些东西不起作用时,它们会很有用。这是它的样子:

    where index' :: Bool
          index' = and [x `elem` a | x <- b]

答案 1 :(得分:2)

Haskell中的if构造是一个表达式。 这意味着它必须始终评估为一个值,因此else部分是必需的。

此外,if的第一部分必须是布尔值,因此您无法在其中调用index',因为它会返回[Int],而不是Bool

我想说,从这样的事情开始:

if isEmpty a
then putStrLn "a is empty"
else if isEmpty b
     then putStrLn "b is empty"
     else putStrLn "neither are empty"

答案 2 :(得分:0)

Haskell中的IO操作有点困难,因为它们需要所谓的monads 你需要一个特殊的do - 概念来对输出进行排序。

像这样写:

empty [] = True
empty _ = False

index a b = do
         if empty a
          then do putStrLn "a is empty"
          else return ()
         if empty b
          then do putStrLn "b is empty"
          else return ()

或者也许您可以返回字符串并单独使用putStrLn。 当index'应该用作if条件时,{{1}}必须返回一个布尔值!

答案 3 :(得分:0)

index a b = if index' [] bs
                       then putStrLn "a is empty"
                       if index' a []          
                        then putStrLn "b is empty"
                        else                  
    where 
        index' :: [String] -> [String] -> [Int]
        index' a b = index' True [(elem x b) | x <- a]

如果你这样缩进你的陈述,你会看到第一个if没有匹配的else子句。

此外,else子句不返回任何内容 - 函数在所有情况下都应具有返回值。