我的 haskell 代码有什么问题?
What is the problem with my haskell code?
Implement some :: [Bool] -> Bool function that decides conditions a list of whether it has a true element. In this task, the or function its use is not permitted.
- 测试:
- some [succ 'a' / = 'b', 1 + 1 / = 2, 10 <20] == True
- some [succ 'a' / = 'b', 1 + 1 / = 2, 10> = 20] == False
- 一些[] ==假
some :: [Bool] -> Bool
some [] = False
some (False: _) = False
some (_: False) = False
some _ = True
如何修复我的代码?不知道是什么问题。
some :: [Bool] -> Bool
some [] = False
some (False:xs) = some xs
some (True:_) = True
您当前代码的问题在于,如果您看到第一个元素是 False
,则不会进一步递归。当您看到 False
时,您必须继续检查列表的其余部分,直到列表耗尽或找到 True
。每当您找到 True
时,您都可以提前退出,只需 return 一个 True
,因为您不关心其余的。
在模式(x:xs)
中,x
是列表的第一项,xs
是剩余元素的列表。这样的列表可以不是是False
。一个列表可能包含 False
个值,但不是 Bool
.
你some
因此看起来像:
some :: [Bool] -> Bool
some [] = False
some (x:xs) = <strong>x || some xs</strong>
Implement some :: [Bool] -> Bool function that decides conditions a list of whether it has a true element. In this task, the or function its use is not permitted.
- 测试:
- some [succ 'a' / = 'b', 1 + 1 / = 2, 10 <20] == True
- some [succ 'a' / = 'b', 1 + 1 / = 2, 10> = 20] == False
- 一些[] ==假
some :: [Bool] -> Bool
some [] = False
some (False: _) = False
some (_: False) = False
some _ = True
如何修复我的代码?不知道是什么问题。
some :: [Bool] -> Bool
some [] = False
some (False:xs) = some xs
some (True:_) = True
您当前代码的问题在于,如果您看到第一个元素是 False
,则不会进一步递归。当您看到 False
时,您必须继续检查列表的其余部分,直到列表耗尽或找到 True
。每当您找到 True
时,您都可以提前退出,只需 return 一个 True
,因为您不关心其余的。
在模式(x:xs)
中,x
是列表的第一项,xs
是剩余元素的列表。这样的列表可以不是是False
。一个列表可能包含 False
个值,但不是 Bool
.
你some
因此看起来像:
some :: [Bool] -> Bool
some [] = False
some (x:xs) = <strong>x || some xs</strong>