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

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

    Another use is to implement class member functions that have a dummy argument which should not be evaluated (used to resolve ambiguous types). Example that could be in Data.bits:

    instance Bits Int where
      isSigned = const True
      bitSize  = const wordSize
      ...
    

    By using const we explicitly say that we are defining constant values.

    Personally I dislike the use of dummy parameters, but if they are used in a class then this is a rather nice way of writing instances.

    0 讨论(0)
  • 2020-12-12 19:30

    Say you want to create a list of Nothings equal to the length of a string. As const returns its first argument, no matter the second, you can do:

    listOfNothings :: String -> [Maybe Char]
    listOfNothings = (map . const) Nothing
    

    or, more explicitly:

    listOfNothing st = map (const Nothing) st
    
    0 讨论(0)
  • 2020-12-12 19:32

    It's useful for passing to higher-order functions when you don't need all their flexibility. For example, the monadic sequence operator >> can be defined in terms of the monadic bind operator as

    x >> y = x >>= const y
    

    It's somewhat neater than using a lambda

    x >> y = x >>= \_ -> y
    

    and you can even use it point-free

    (>>) = (. const) . (>>=)
    

    although I don't particularly recommend that in this case.

    0 讨论(0)
提交回复
热议问题