All combinations of elements of two lists in Haskell

前端 未结 5 1091
情歌与酒
情歌与酒 2020-12-30 03:42

Given two lists, [a, b] and [c, d], I\'d like to get the following result:

[(a,c), (a,d), (b         


        
5条回答
  •  感情败类
    2020-12-30 04:15

    Applicative style all the way!

    λ> :m + Control.Applicative
    λ> (,) <$> ['a','b'] <*> ['c','d']
    [('a','c'),('a','d'),('b','c'),('b','d')]
    

    (I've eschewed any String syntactic sugar above, in order to stay close to your example.)

    For information, (,) is special syntax for a function that takes two arguments and makes a pair out of them:

    λ> :t (,)
    (,) :: a -> b -> (a, b)
    

    Edit: As noted by leftaroundabout in his comment, you can also use liftA2:

    λ> :m + Control.Applicative
    λ> let combine = liftA2 (,)
    λ> combine "ab" "cd"
    [('a','c'),('a','d'),('b','c'),('b','d')]
    

提交回复
热议问题