简体   繁体   English

在 haskell 中创建具有多个条件的列表

[英]Creating list with multiple conditions in haskell

Define the sequence (bn)n=1,2,… such that bn=3 when n is divisible by 3, and bn=4(n+1)^2 in other cases.定义序列 (bn)n=1,2,… 使得当 n 可被 3 整除时 bn=3,而在其他情况下 bn=4(n+1)^2。 Define a function that for an argument n creates the list of n initial numbers of the sequence (bn)n=1,2,….定义一个 function,它为参数 n 创建序列 (bn)n=1,2,... 的 n 个初始数字的列表。

so far I have two lists with condition 1 and condition 2:到目前为止,我有两个条件 1 和条件 2 的列表:
divisible3 n = [x | x <- [1..n], x `mod` 3 == 0]
notdivisible3 n = [x*x*4+8*x+4 | x <- [1..n], x `mod` 3 /= 0]
I want it to be one list like:我希望它是一个列表,例如:
list n = [x | x <- [1..n], condition1, condition 2]

You should write an if... then... else... in the "yield" part of the list comprehension, not a filter.你应该在列表理解的“yield”部分写一个if... then... else... ,而不是一个过滤器。 So something like:所以像:

list n = [ if n `mod` 3 == 0 then … else … | x <- [1..n]]

where I leave the parts as an exercise.我把部分留在那里作为练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM