我想为整数列表中的每个元素编写一个函数,如果元素为正,则将其乘以 100,如果不是,则将其与另一个整数列表中的每个元素相乘。然后我们将结果打包成一个列表。例如,对于列表 [1, 2, -1]
和 [100, 200]
,我们有最终列表 [100, 200, -100 , -200]
我打算使用列表理解,但我不知道如何在另一个列表中工作,[100, 200]
。到目前为止我得到了:
toyFunc :: [Int] -> [Int]
toyFunc lst_int =
[let res =
if elem > 0 then elem *100 else ------> how to write this else part?
in res | elem <- lst_int]
代码不工作,但是否可以修复它,或者是否有更好的结构来解决这个问题?
最佳答案
使用 concatMap
怎么样? concatMap
类似于 map
,但强制结果类型为列表。然后,将结果列表粘合在一起(扁平化)。如果你使用 concatMap
就很容易了:
toyFunc :: [Int] -> [Int] -> [Int] -- Recall, that you have two lists
toyFunc list replacement = concatMap mapper list where
mapper x | x > 0 = [x * 100]
| otherwise = map (*x) replacement
关于haskell - 我该如何编写这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6623000/