What's the point of 'const' in the Haskell Prelude?

后端 未结 9 1189
不思量自难忘°
不思量自难忘° 2020-12-12 18:50

Looking through the Haskell Prelude, I see a function const:

const x _ = x

I can\'t seem to find anything relevant regarding t

9条回答
  •  春和景丽
    2020-12-12 19:07

    I can't seem to find anything relevant regarding this function.

    Suppose you would like to generate all subsequences of a given list.

    For each list element, at a given point you have a choice of True (include it in the current subsequence) or False (do not include it). This can be done using the filterM function.

    Like this:

     λ> import Control.Monad
     λ> :t filterM
     filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
     λ> 
    

    For example, we want all the subsequences of [1..4].

     λ> filterM  (const [True, False])  [1..4]
     [[1,2,3,4],[1,2,3],[1,2,4],[1,2],[1,3,4],[1,3],[1,4],[1],[2,3,4],[2,3],[2,4],[2],[3,4],[3],[4],[]]
     λ> 
    

提交回复
热议问题