OrenIshShalom
OrenIshShalom

Reputation: 7172

Haskell function with no input arguments

How can I define a function that takes no arguments?

data Address
   = Address
   {
       city :: String,
       street :: String
   }
   deriving ( Show )

-- mkIncompleteAddress :: () -> Address
-- mkIncompleteAddress = Address "NYC" "<TBD>"

mkIncompleteAddress :: Address
mkIncompleteAddress = Address "NYC" "<TBD>"

The closest I can get is a constant (?) global variable (?) When I remove the comments I get:

Main.hs:10:23: error:
    • Couldn't match expected type ‘() -> Address’
                  with actual type ‘Address’
    • Possible cause: ‘Address’ is applied to too many arguments
      In the expression: Address "NYC" "<TBD>"
      In an equation for ‘mkIncompleteAddress’:
          mkIncompleteAddress = Address "NYC" "<TBD>"

Upvotes: 1

Views: 371

Answers (1)

bradrn
bradrn

Reputation: 8477

mkIncompleteAddress :: Address is a function which takes no arguments. In Haskell, that’s more or less the same thing as a global constant, since non-IO functions don’t have side-effects and values are lazily evaluated.

On the other hand, it’s still entirely possible to write a function mkIncompleteAddress :: () -> Address, like so:

mkIncompleteAddress :: () -> Address
mkIncompleteAddress x = Address "NYC" "<TBD>"

Or, you can be really explicit and pattern-match on the input:

mkIncompleteAddress :: () -> Address
mkIncompleteAddress () = Address "NYC" "<TBD>"

Syntactically, this looks a bit like a function with no arguments, but it isn’t: it’s a function which requires one argument, where this argument happens to have () as its only value.


However, I would invite you to reconsider your approach here. Address "NYC" "<TBD>" is, quite obviously, invalid as an address, and using such values in your program just makes mistakes easier to make. I’d recommend doing something like this instead:

mkIncompleteAddress :: String -> Address
mkIncompleteAddress street = Address "NYC" street

Or even simpler, taking advantage of currying:

mkIncompleteAddress :: String -> Address
mkIncompleteAddress = Address "NYC"

Upvotes: 3

Related Questions