Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Default values" for Haskell function?

Tags:

haskell

Is there any way that input values to a function can be pre-defined so that a user doesn't have to define them each time?

For example, assuming I had a function "zr" which returned a list zeros of size n, such that:

zr 1 = [0]
zr 5 = [0, 0, 0, 0, 0]

And so on.

My current way of implementing it is:

zr :: [Int] -> Int -> [Int]
zr x y
    | length x == y = x
    | otherwise = zr x++[y]

But this isn't particularly elegant as every time I call zr I need to include an empty list as a parameter:

zr [] 5

Any ideas?

Thanks!

like image 478
Dario Avatar asked May 06 '14 08:05

Dario


People also ask

What is Haskell function?

Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output.

What does ++ do Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.

What is a value in Haskell?

A value is the result of evaluating an expression. In Haskell there is no distinction between expressions whose result is a function and the ones that return some data values. A function name is already a valid expression, it's easy to construct anonymous functions etc.

Does every Haskell function terminate?

> Haskell allows non-terminating "functions", for example. Non-terminating functions are still pure functions in the mathematical sense. While it does somewhat complicate the use of programs as proofs, a pure function doesn't need to have a defined value for every possible input.

Does Haskell have variables?

Within a given scope, a variable in Haskell gets defined only once and cannot change. The variables in Haskell seem almost invariable, but they work like variables in mathematics. In a math classroom, you never see a variable change its value within a single problem.


1 Answers

I think what you're looking for is partial application:

zr' :: Int -> [Int]
zr' = zr []

If zr is a function that takes a list and an integer, then zr [] is a function that takes only an integer n and returns zr [] n.

In your case, zr is obviously a "temporary" function (you don't want anyone calling zr [1] 4 by accident), so you might as well define it locally:

zr :: Int -> [Int]
zr = zr' []
  where
     zr' :: [Int] -> Int -> [Int]
     zr' x y
         | length x == y = x
         | otherwise = zr' x++[0] y
like image 99
Benesh Avatar answered Sep 24 '22 20:09

Benesh