簡體   English   中英

如果在haskell中則嵌套

[英]nested if in haskell

//當我僅使用這兩行時編輯5

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

它工作正常!

例如:

索引[“ 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]

謝謝

這有點不合時宜,因為您可能正在嘗試學習布局規則以及如何嵌套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]

(您不需要在putStrLn之后return () ,因為它已經為您返回() 。)

模式匹配更容易實現,因為它不需要很多縮進等。


編輯:

我對index'的定義稍有改動。 在我的版本中,它是一個局部變量而不是局部函數。 在Haskell中,沒有太大的區別,只是index'使用周圍index函數中的ab ,因此不需要參數。 (不可否認, index'並不是變量的好名字。)

另外,由於我通常不編寫類型注釋,因此我放棄了類型注釋。 但是,當某些問題不起作用時,它們會有所幫助。 看起來像這樣:

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

Haskell中的if構造是一個表達式。 這意味着它必須始終求值,因此else部分是強制性的。

另外, if的第一部分必須是布爾值,因此您不能index'此處調用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"

在Haskell IO操作是有點困難,因為他們需要所謂的單子 ,您將需要一個專門do -notion這里進行排序輸出。

像這樣寫:

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'必須返回一個布爾值!

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子句不返回任何內容-函數在所有情況下都應具有返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM