Replace a 3 parameter list-comprehension by using map, concat

前端 未结 3 1372
感情败类
感情败类 2021-01-16 18:14

I have some understanding of list comprehension. I understand that the expression:

[x * x | x <- [1..10]]
should output [1,4,9,16,25,36,49,64,81,100]
         


        
3条回答
  •  甜味超标
    2021-01-16 19:12

    [(x,y+z) | x <- [1..10], y <- [1..x], z <- [1..y]]
    

    is the same as

    concatMap
        (\x -> [(x,y+z) | y <- [1..x], z <- [1..y]])
        [1..10]
    

    You can extract the y and z variables out of the list comprehension similarly. (But you must do it in order from left to right: so y next and z last.)

    concatMap is a function defined in the Prelude:

    concatMap :: (a -> [b]) -> [a] -> [b]
    concatMap f = concat . map f
    

提交回复
热议问题