我想编写一个函数,有效地告诉我,当列表中的项目是在一个范围内的所有项目可分与否.问题是,我不知道在遇到false时立即停止列表理解.
allDivisByRng n start stop =
[n `mod` x == 0 | x <- [start, start+1 .. stop]]
Run Code Online (Sandbox Code Playgroud)
我已经尝试过,takeWhile但却无法做到我想做的事情.请指教.
allDivisByRng n start stop =
takeWhile( == True ) [ n `mod` x == 0 | x <- [start, start+1.. stop] ]
Run Code Online (Sandbox Code Playgroud)
当我跑步时,allDivisByRng 10 2 4我得到了一份真实的名单
其他一些样本运行
*Main> allDivisByRng 12 2 10
[True,True,True]
*Main> allDivisByRng 12 2 150
[True,True,True]
-- I want this to return false
*Main> allDivisByRng 2520 2 10
[True,True,True,True,True,True,True,True,True]
-- I want this to return True
Run Code Online (Sandbox Code Playgroud)
我也试过寻找 False
allDivisByRng n start stop =
takeWhile( == False ) [ n `mod` x == 0 | x <- [start, start+1.. stop] ]
*Main> allDivisByRng 10 2 3
[]
-- want false to be returned
*Main> allDivisByRng 10 2 10
[]
-- want false to be returned
*Main> allDivisByRng 2520 2 10
[]
-- want true to be returned
*Main> allDivisByRng 12 2 10
[]
-- want false to be returned
Run Code Online (Sandbox Code Playgroud)
功能all,
all :: Foldable t => (a -> Bool) -> t a -> Bool
Run Code Online (Sandbox Code Playgroud)
允许您检查可折叠结构的所有元素是否满足特定条件.在你的情况下,
allDivisByRng n start stop = all ((== 0) . (mod n)) [start..stop]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |