When ... do --vs-- if ... then do ... else

In Haskell monadic code, I can have

if bool then do
else

but in Purescript (such as in monadic Halogen eval), I get compiler error unless I use

when bool do

and thus do not have use of an else clause. Am I missing something?

1 Like

You can do if-else inside do notation: here is an example:
http://try.purescript.org/?session=225c37a0-c0c5-accf-a2d6-b8b624f036fc

module Main where

import Prelude

import Control.Monad.Eff (Eff)
import Data.Foldable (fold)
import TryPureScript (DOM, h1, h2, p, text, list, indent, link, render, code)

main :: Eff (dom :: DOM) Unit
main = do
    if true
      then do render $ h1 (text "True is true")
      else pure unit

maybe the indentation is giving you difficulties?

1 Like

I am not sure what my problem is, but is when do the same as if then do? And how would you indent a multi-line then do, and can you have then do without an else?

When itself is a function :: Boolean -> m Unit -> m Unit
You can see the source of when here

As I understand, when <condition> do <something> would act like:

if <condition>
  then do <something>
  else pure unit

So in TryPurescript you can indent it like this

module Main where

import Prelude

import Control.Monad.Eff (Eff)
import Data.Foldable (fold)
import TryPureScript (DOM, h1, h2, p, text, list, indent, link, render, code)

main :: Eff (dom :: DOM) Unit
main = do
    if true
      then do 
        render $ h1 (text "True is true")
        render $ h2 (text "True is still true")
      else pure unit
    render $ h2 (text "Outside of the inner do")

This would be equivalent to

main :: Eff (dom :: DOM) Unit
main = do
    when true
      do 
        render $ h1 (text "True is true")
        render $ h2 (text "True is still true")
    render $ h2 (text "Outside of the inner do")
1 Like

Thanks for your help.