Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Functions that sometimes return a function

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)
like image 756
Jonathan Allen Avatar asked Jul 04 '10 01:07

Jonathan Allen


People also ask

What is a curried function Haskell?

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.

Can a Haskell function return nothing?

No. However, you can have functions that return a trivial value. The () type has only one inhabitant, () .

Does Haskell have return?

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.

Can a function return multiple values Haskell?

Yes, you can return multiple values with a haskell construct called a tuple.


1 Answers

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.

like image 120
sepp2k Avatar answered Sep 24 '22 21:09

sepp2k