本文介绍了使用或在列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在尝试将1至10之间的每个数字都除以5或3 来整除这里是我的代码,直到现在 - giveList = [x | x (x`mod`5 == 0)或(x`mod`3 == 0)] 然后我用ghci加载函数。但它给了我一个错误 - > [1 of 1]编译Main(problem1.hs,解释) problem1.hs:4:10:函数`x`mod` 5 == 0'适用于两个参数但其类型Bool没有在表达式中:(x`mod` 5 == 0)或(x`mod` 3 == 0)在句柄的列表理解:(x`mod` 5 == 0)或(x`mod` 3 == 0)在表达式中: [x | x 失败,加载模块:无。 我的问题是 - 我们可以在列表解析中使用'或'吗? 如果不是,请告诉我如何以其他方式完成。 b 我是函数式编程新手,请帮助我。 解决方案 您可以在列表解析中使用或,但 Prelude> :t或或:: [Bool] - > Bool 这不是你在那个地方需要的那个,它是一个函数,该列表是 True 。您需要 (||):: Bool - >布尔 - > Bool 如果要使用名称由字母中缀组成的函数,则需要附上它反引号,就像你对 mod 做的一样,但是既然或者只有一个参数,你就不能使用这个函数中缀。 您的清单的正确版本为 giveList = [x | x I'm trying to take out every number between 1 to 10 that is divisible by either 5 or 3Here is my code till now - giveList = [ x | x <- [1..10] , (x `mod` 5 == 0) or (x `mod` 3 == 0)]And then I load the function in ghci. But it's giving me a error - > [1 of 1] Compiling Main ( problem1.hs, interpreted )problem1.hs:4:10: The function `x `mod` 5 == 0' is applied to two arguments, but its type `Bool' has none In the expression: (x `mod` 5 == 0) or (x `mod` 3 == 0) In a stmt of a list comprehension: (x `mod` 5 == 0) or (x `mod` 3 == 0) In the expression: [x | x <- [1 .. 10], (x `mod` 5 == 0) or (x `mod` 3 == 0)]Failed, modules loaded: none.My question is -Can we use 'or' in list comprehensions?If not, please tell me how it can be done in other waysI'm new to functional programming, please help me. 解决方案 You can use or in list comprehensions, butPrelude> :t oror :: [Bool] -> Boolthat is not the one you need at that place, it's a function that checks whether any element in the list is True. There you need(||) :: Bool -> Bool -> BoolAnd if you want to use a function with a name consisting of letters infix, you need to enclose it in backticks, like you did with mod, but since or takes only one argument, you cannot apply that function infix.A correct version of your list would begiveList = [ x | x <- [1 .. 10], x `mod` 5 == 0 || x `mod` 3 == 0] 这篇关于使用或在列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-02 12:24