How to write Haskell function with no parameter?

Viewed 2242

I have a function declaration called e6. I need to replace undefined by some code and make it work.

e6 :: Int -> Int -> Int
e6 = undefined

I know for example

add :: Int -> Int -> Int
add a b = a + b

It takes parameters a and b then return a + b. But how can I write a function with no argument. I tried

e6 :: Int -> Int -> Int
e6 = 2 + 3

And it said:

No instance for (Num (Int -> Int -> Int)) arising from a use of '+'

2 Answers

It's not super clear what the right fix is, because it's not super clear to me exactly what you want. Here are some possible interpretations of what you want.

  • You want e6 to be equivalent to the constant 5, computed by evaluating 2+3. Since this is not a function, you should not use a function type in its signature.

    e6 :: Int
    e6 = 2 + 3
    
  • You want e6 to be a function just like add is, but to always return 2+3 instead of a+b -- that is, to ignore its arguments, even though it still has them. Then the type signature is okay, but you need to explicitly ignore the arguments.

    e6 :: Int -> Int -> Int
    e6 _ _ = 2 + 3
    -- OR
    e6 a b = 2 + 3
    
  • You want e6 to be just like add in every way, but you don't want to explicitly name its arguments when defining e6. Then, if you're not giving the arguments to e6, you also can't give the arguments to +. So:

     e6 :: Int -> Int -> Int
     e6 = (+)
    

    (+) is special syntax for turning an infix operator into a prefix function; roughly, \a b -> (+) a b and \a b -> a + b behave the same way.

Are you asking about how to write a function in point-free style?

If so, you can write the addition function as:

e6 = (+)

In this simple example, e6 simply becomes an alias for the + operator. In Haskell, operators are just functions with special names, and when you want to use them as functions instead of operators, you surround them with brackets, as above. The (+) function (i.e. + operator) is already a function that takes two arguments, and returns a value.

Here's a bit of GHCi interaction with it:

Prelude> :t e6
e6 :: Num a => a -> a -> a
Prelude> e6 1 3
4
Prelude> e6 42 1337
1379

The inferred type is Num a => a -> a -> a, but this is also compatible with Int -> Int -> Int, so if you wish to constrain the type to that, you can declare the function with this more restricted type. There's no particular reason to do that, though, since the generic version works fine with Int as well, as the GHCi session demonstrates.

Related