I think that LOST is right:

1
2
3
4
5
6
7
8
9
let rec maybeSquareEvery l =
  maybe {
    match l with
    | [] -> return []
    | h::t ->
        let! h' = maybeSquare h
        let! t' = maybeSquareEvery t
        return h'::t'
  }

Also, note that if you add a

1
member b.Zero() = fail

to your

1
MaybeBuilder

, then you can express

1
maybeSquare

more naturally as

1
2
3
let maybeSquare n = maybe {if n <= 1000 then return n * n}

or

1
let maybeSquare n = maybe {if n > 1000 then () else return n * n}
By on 1/11/2011 7:18 AM ()

Thank you both. So, as far as I understand it, there is no standard, idiomatic way to sweeten that syntax. That was the essence of my question if you wish : )

As for your suggestion for b.Zero()--in real life, a failure carries data indicating what the failure was, so there is no sensible zero in my case of Maybe<_>.

By on 1/11/2011 12:27 PM ()

I don't quite understand what the problem is. I would use the maybe monad, and define a couple of maybe higher-order functions. Given that, you should be able to write nice iterative code that stops as soon as some iteration fails.
Note that you can also override the semantics of for and while loops using members For and While in your workflow builder. If you've got while, for, recursion and higher order functions covered, what more would you need?

By on 1/11/2011 9:41 PM ()

Thanks, that was what I did in the end.

By on 1/12/2011 4:39 AM ()

I've never used computation expressions in F#, but I think your maybeSquareEvery function must be recursive.
Supposing it is recursive, // Magic! can be that:

1
2
3
4
5
6
match nl with
| [] -> []
| head:: tail ->
  let! h = maybeSquare head
  let! t = maybeSquareEvery tail
  h :: t

Note this is not tail recursive version.

By on 1/11/2011 6:06 AM ()

Thanks. The problem is that I need to perform many calculations, and not all of them are map-type applications of function to lists. This is why I am looking for a more expressive idiom, which maybe { } would allow -- except for iterative applications.

I perfectly understand how to write the whole thing without CE, but it becomes ugly -- and I mean ugly!

By on 1/11/2011 6:38 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper