[Haskell-cafe] Fwd: [Haskell-beginners] monad and variable result

Seph Shewell Brockway seph at codex.scot
Mon Dec 10 16:19:39 UTC 2018


Hi Damien,

On Mon, Dec 10, 2018 at 03:18:48PM +0100, Damien Mattei wrote:
> have some code that works but want to put it in a simple function
> without sucess:
> 
> getBD :: Connection -> String -> Float
> getBD conn name = noBDfp
>   where qry_head = "select `N° BD` from sidonie.Coordonnées where Nom =
> ?" :: Query
>         bd_rows = do
>           local_bd_rows <- query conn qry_head (Only (name::String))
>           return local_bd_rows
> 
> 
> i want  the variable local_bd_rows accessible in the 'where' clause
> 
> how can i do that?

You don’t seem to be using the function bd_rows anywhere in the main
body of the definition. You would need to do something like

         getBD :: Connection -> String -> IO Float
         getBD = do rows <- bd_rows
            {- code that does something with the returned data -}

Note the change to the type signature—querying the database is an IO
action, and therefore takes place in the IO monad.

Incidently, your use of do notation in the definition of bd_rows is
unnecessary:

   do x <- doSomething
      return x

is actually syntactic sugar for

   doSomething >>= \x -> return x

which the monad laws state is equivalent to just doSomething. This is a
common misapprehension among Haskell novices: the do notation is just a
syntactic convenience, and it is perfectly possible to write monadic
functions, including in the IO monad, without it.
            
Hope at least some of this helps.

Seph

-- 
Seph Shewell Brockway, BSc MSc (Glas.)


More information about the Haskell-Cafe mailing list