What is () in Haskell, exactly?

前端 未结 6 1636
星月不相逢
星月不相逢 2020-12-12 15:55

I\'m reading Learn You a Haskell, and in the monad chapters, it seems to me that () is being treated as a sort of \"null\" for every type. When I check

6条回答
  •  醉酒成梦
    2020-12-12 15:58

    The () type can be thought of as a zero-element tuple. It's a type that can only have one value, and thus it's used where you need to have a type, but you don't actually need to convey any information. Here's a couple of uses for this.

    Monadic things like IO and State have a return value, as well as performing side-effects. Sometimes the only point of the operation is to perform a side-effect, like writing to the screen or storing some state. For writing to the screen, putStrLn must have type String -> IO ? -- IO always has to have some return type, but here there's nothing useful to return. So what type should we return? We could say Int, and always return 0, but that's misleading. So we return (), the type that has only one value (and thus no useful information), to indicate that there's nothing useful coming back.

    It's sometimes useful to have a type which can have no useful values. Consider if you'd implemented a type Map k v which maps keys of type k to values of type v. Then you want to implement a Set, which is really similar to a map except that you don't need the value part, just the keys. In a language like Java you might use booleans as the dummy value type, but really you just want a type that has no useful values. So you could say type Set k = Map k ()

    It should be noted that () is not particularly magic. If you want you can store it in a variable and do a pattern match on it (although there's not much point):

    main = do
      x <- putStrLn "Hello"
      case x of
        () -> putStrLn "The only value..."
    

提交回复
热议问题