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

后端 未结 9 1192
不思量自难忘°
不思量自难忘° 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:23

    A simple example for using const is Data.Functor.(<$). With this function you can say: I have here a functor with something boring in it, but instead I want to have that other interesting thing in it, without changing the shape of the functor. E.g.

    import Data.Functor
    
    42 <$ Just "boring"
    --> Just 42
    
    42 <$ Nothing
    --> Nothing
    
    "cool" <$ ["nonsense","stupid","uninteresting"]
    --> ["cool","cool","cool"]
    

    The definition is:

    (<$) :: a -> f b -> f a
    (<$) =  fmap . const
    

    or written not as pointless:

    cool <$ uncool =  fmap (const cool) uncool
    

    You see how const is used here to "forget" about the input.

提交回复
热议问题