Using the for expression in Scala for Monad operations

Source: Internet
Author: User

In Haskell, we have the syntax sugar ' do ' to help express the monad operation. We also have the corresponding syntax sugar ' for ' in Scala.

The for expression will be transformed by Scala compiler, with the following simple examples:

 for {  <- foo  <-yield (A + B)

===>

Foo.flatmap ((a) + =  {= =     {+ b  })})

So we need to implement two methods Flatmap and map.

or using the previous state Monad as an example, we add flatmap and map to the type State.

 Case class State[s, a] (runstate:s = (S, A)) (implicit m:monad[({type m[a] = state[s, A]}) #M]) {  = = B) : State[s, b] = M.bind (This, (A:A) and M.ret (f (a)))  = State[s, b]): State[s, b] = M.bind (
   
    this
    , f)}
   

Here we use an implicit parameter, and then we can use RET and bind directly.

Add a helper to simplify monad[({type m[a] = State[s, A]}) #M].ret

Def Ret[s, A] (A:A): State[s, A] = monad[({type m[a] = State[s, A]}) #M].ret (a)

Well, we can use the for expression, as in the following example:

Object Main {    import statemonad._    def main (args:array[string]) {    for  {        <-ret [int, int] (3)         <-Ret[int, Int] (4)    yield (A +b)    println (r.runstate (  1)  }}

Using the for expression in Scala for Monad operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.