表达式中的语法 - Haskell

pie*_*ier 0 haskell if-statement

我是哈斯克尔新手!我写了这段代码:

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

没有if语句它工作正常,但当我把if语句显示以下错误时:

表达式中的语法错误(意外的`}',可能是由于布局错误)

我在这做错了什么?

谢谢

Ste*_*202 8

这里有几件事是错的:

  • 需要一个else子句.
  • True 必须资本化.
  • inputIndex 必须总是带两个参数(现在它不会,在最后一种情况下).

我想你想要这样的东西......

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]
Run Code Online (Sandbox Code Playgroud)

(这里我通过附加一个素数/撇号来定义一个名称几乎相同的新函数.通过在where子句中定义它,它只对外部inputIndex函数可见.如果愿意,你可以将它称为辅助函数.我也可以选择一个完全不同的名字,但我没有创意.)

您还可以将其浓缩为以下内容(这也更通用):

allPresent :: (Eq t) => [t] -> [t] -> IO ()
allPresent xs ys = putStrLn (if and [y `elem` xs | y <- ys] then "ok" else "not ok")
Run Code Online (Sandbox Code Playgroud)

  • @dlna你真的需要坐下来看一本Haskell书并找出该代码的每一行实际上做了什么,如果你必须评论一个没有它的类型定义的函数. (2认同)