What does the “Just” syntax mean in Haskell?

后端 未结 5 1611
说谎
说谎 2020-12-07 08:33

I have scoured the internet for an actual explanation of what this keyword does. Every Haskell tutorial that I have looked at just starts using it randomly and never explain

5条回答
  •  旧巷少年郎
    2020-12-07 08:51

    Given a type t, a value of Just t is an existing value of type t, where Nothing represents a failure to reach a value, or a case where having a value would be meaningless.

    In your example, having a negative balance doesn't make sense, and so if such a thing would occur, it is replaced by Nothing.

    For another example, this could be used in division, defining a division function that takes a and b, and returns Just a/b if b is nonzero, and Nothing otherwise. It's often used like this, as a convenient alternative to exceptions, or like your earlier example, to replace values that don't make sense.

提交回复
热议问题