Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use IO Bool in if-statement without binding to a name in haskell?

Tags:

haskell

monads

If I've got a function that returns IO Bool (specifically an atomically), is there any way to use the return value directly in the if statement, without binding?

So currently I've got

ok <- atomically $ do
  ...
if (ok) then do
  ...
else do
  ...

Is it at all possible to write this as something like

if (*some_operator_here* atomically $ do
      ...) then do
  ...
else do
  ...

I was hoping there'd be a way to use something like <- anonymously, i.e., if (<- atomically ...) but so far no such luck.

Similarly on getLine, is it possible to write something like

if ((*operator* getLine) == "1234") then do ...

Related addendum--what is the type of (<-)? I can't get it to show up in ghci. I'm assuming it's m a -> a, but then that would mean it could be used outside of a monad to escape that monad, which would be unsafe, right? Is (<-) not a function at all?

like image 460
Dax Fohl Avatar asked Jun 06 '13 01:06

Dax Fohl


People also ask

How does Haskell handle IO?

Haskell separates pure functions from computations where side effects must be considered by encoding those side effects as values of a particular type. Specifically, a value of type (IO a) is an action, which if executed would produce a value of type a .

How is IO pure in Haskell?

Calculations involving such operations cannot be independent - they could mutate arbitrary data of another computation. The point is - Haskell is always pure, IO doesn't change this. So, our impure, non-independent codes have to get a common dependency - we have to pass a RealWorld .

Is IO a Monad Haskell?

The IO type constructor provides a way to represent actions as Haskell values, so that we can manipulate them with pure functions. In the Prologue chapter, we anticipated some of the key features of this solution. Now that we also know that IO is a monad, we can wrap up the discussion we started there.

How does IO Monad work?

The I/O monad contains primitives which build composite actions, a process similar to joining statements in sequential order using `;' in other languages. Thus the monad serves as the glue which binds together the actions in a program.


1 Answers

You can use ifM from Control.Conditional if that suits your purpose and its not even hard to write a similar function.

Just to give you example

import Control.Conditional
import Control.Monad

(==:) :: ( Eq a,Monad m) => m a -> m a -> m Bool
(==:) = liftM2 (==)

main = ifM (getLine ==: getLine) (print "hit") (print "miss")

I think there are ways using rebindable syntax extension that you can even use if c then e1 else e2 like syntax for ifM but it is not worth the effort to try that.

like image 163
Satvik Avatar answered Sep 19 '22 06:09

Satvik