What does the “Just” syntax mean in Haskell?

后端 未结 5 1617
说谎
说谎 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:56

    Most of the current answers are highly technical explanations of how Just and friends work; I thought I might try my hand at explaining what it's for.

    A lot of languages have a value like null that can be used instead of a real value, at least for some types. This has made a lot of people very angry and been widely regarded as a bad move. Still, it's sometimes useful to have a value like null to indicate the absence of a thing.

    Haskell solves this problem by making you explicitly mark places where you can have a Nothing (its version of a null). Basically, if your function would normally return the type Foo, it instead should return the type Maybe Foo. If you want to indicate that there's no value, return Nothing. If you want to return a value bar, you should instead return Just bar.

    So basically, if you can't have Nothing, you don't need Just. If you can have Nothing, you do need Just.

    There's nothing magical about Maybe; it's built on the Haskell type system. That means you can use all the usual Haskell pattern matching tricks with it.

提交回复
热议问题