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!
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.
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.
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.
> 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With