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

前端 未结 3 1378
感情败类
感情败类 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条回答
  •  猫巷女王i
    2021-01-16 18:54

    You can transform this into do-notation:

    foo = do x <- [1..10]
             y <- [1..x]
             z <- [1..y]
             return (x, y+z)
    

    This works because list is a monad. The do-notation itself is just syntactic sugar for a monadic calculation. Following the desugaring rules (described here under "Desugaring of do blocks") you end up with:

    [1..10] >>= (\x -> [1..x] >>= (\y -> [1..y] >>= (\z -> [(x,y+z)])))
    

    The operator >>= is defined in Control.Monad, and is equivalent to a concatMap with flipped arguments for lists. return t is just [t] in case of lists.

提交回复
热议问题