How do you write a function that can either return a value or another function?
For example:
Function Foo (x)
If X = 0 Return "Done"
Else Return a Function that calls Foo(x-1)
From HaskellWiki. Currying is the process of transforming a function that takes multiple arguments in a tuple as its argument, into a function that takes just a single argument and returns another function which accepts further arguments, one by one, that the original function would receive in the rest of that tuple.
No. However, you can have functions that return a trivial value. The () type has only one inhabitant, () .
return is actually just a simple function in Haskell. It does not return something. It wraps a value into a monad. Looks like return is an overloaded function.
Yes, you can return multiple values with a haskell construct called a tuple.
In haskell the return type of a function can only depend on the type of its arguments and, in case of functions with polymorphic return types, how the return value is used. In particular the return type of the function can not depend on the value of the argument.
In other words: you can't do what you want directly. In cases where you want to return one of two types, you can usually the type Either a b
which is defined as data Either a b = Left a | Right b
, which allows you to return a value of type a
wrapped in a Left
or a value of type b
wrapped in a Right
. You could then use pattern matching to retrieve the value in a type safe manner.
However since in this case the type for b
would have to be infinite this does not work and you have to define your own wrapper type for this. Like so:
data MyResult = Str String | Fun ( () -> MyResult)
foo 0 = Str "done"
foo x = Fun (\ () -> foo (x-1))
foo
now has type Num a => a -> MyResult
. However every time you call foo
you have to pattern match to see whether you got back a Str with a string inside or a Fun with a function inside.
Also note that if you want to return a function rather than a value in order to delay execution, this doesn't make sense in haskell because it is lazy and things generally don't get evaluated before they are used.
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