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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 bwhich is defined asdata Either a b = Left a | Right b, which allows you to return a value of typeawrapped in aLeftor a value of typebwrapped in aRight. You could then use pattern matching to retrieve the value in a type safe manner.However since in this case the type for
bwould have to be infinite this does not work and you have to define your own wrapper type for this. Like so:foonow has typeNum a => a -> MyResult. However every time you callfooyou 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.