'I want a Haskell function (a -> b) -> a -> IO (Maybe b) that tries to evaluate a function and abort if it takes too much time [duplicate]

I am relatively new to Haskell and came across the following problem. Given a function f from a to b (let's say from Int to Int) and an element x in the domain.

Ideally, what I would like to do: If the function f given input x evaluates in finite time to a y, I would like to return "Just y". If the function f given input x enters an infinite loop, I would like to return "Nothing".

I know that this task is impossible as I stated it because the Halting problem is undecidable. But what should be possible is the following: Take a function f, try to evaluate it at input x, try for 5 seconds and if you're not finished after 5 seconds, abort and return Nothing.

Is there a way to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source