What is an idiomatic way to add lists in Haskell?

前端 未结 3 1247
梦谈多话
梦谈多话 2021-01-04 15:44

Suppose I want to add two lists in Haskell. What is the most usual way to do this?

Here\'s what I did:

addLists :: (Integral a) => [a] -> [a]          


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 16:06

    Applicative Functor style:

    import Control.Applicative
    
    addLists xs ys = getZipList $ (+) <$> ZipList xs <*> ZipList ys
    

    Note that this is so ugly because there are two ways to make List an Applicative Functor. The first (and IMHO less useful) way is to take all combination, and that way became the "standard", so (+) <$> [1,2] <*> [30,40] is [31,41,32,42]. The other way is to zip the lists as we need here, but as you can have only one type class instance per type, we have to wrap the lists in ZipLists, and to unwrap the result using getZipList.

提交回复
热议问题