Also see the thread Feature Request: Where construction/clause (from OCaml Batteries Included).

Consider

1
2
3
4
5
let fibo n = fst fibo_aux n
  where rec fibo_aux = function
    | 0 -> (1, 1)
    | 1 -> (1, 2)
    | n -> (a, a + b) where let (a, b) = fibo_aux ( n - 1 )

This extract is equivalent to

1
2
3
4
5
6
7
let fibo n =
  let rec fibo_aux =
    function
    | 0 -> (1, 1)
    | 1 -> (1, 2)
    | n -> let (a, b) = fibo_aux (n - 1) in (a, (a + b))
  in fst (fibo_aux n)
By on 5/29/2009 8:36 AM ()

You could define an infix operator that applies effects to the LHS before returning it.

1
2
3
4
5
6
7
8
9
10
11
let (&>) x f = f x; x

let example () =
    System.Windows.Forms.Form() &> (fun f ->
        f.Visible <- true
        f.Opacity <- 0.5)

let zoomTransform zoom scaled =
    ScaleTransform() &> (fun t -> t.SetValue(ScaleTransform.ScaleXProperty, zoom)
                                  t.Value.TranslatePrepend(-scaled.X, -scaled.Y))
By on 5/29/2009 9:22 AM ()

and you can drop the brackets around the RHS fun-expr.

1
2
3
4
5
6
7
8
9
10
11
12
13
let (&>) x f = f x; x

let example () =
    System.Windows.Forms.Form() &> fun f ->
        f.Visible <- true
        f.Opacity <- 0.5


let zoomTransform zoom scaled =
    ScaleTransform() &> fun t ->
        t.SetValue(ScaleTransform.ScaleXProperty, zoom)
        t.Value.TranslatePrepend(-scaled.X, -scaled.Y)
By on 5/29/2009 9:28 AM ()

This is a very smart technique!

Unfortunately until we have minimal tooling support for operators (e.g. Intellisense, Goto Definition) I'm very reluctant to define any operator whose meaning isn't immediately and unambiguously apparent from its context. The &> operator could be construed as obfuscating.

In conclusion I hope the FSharp team would consider implementing this extended 'as' idiom and the 'where' clause as they both promote clarity of the code, (which I believe to be a very important concern.)

regards,

Danny

By on 6/1/2009 12:47 AM ()

Isn't the (&>) operator you just defined the |> pipe operator.

I do use this idiom alot except I use |>.

It makes it nice to define additional helper functions and values that don't polute the name space above it.

By on 5/29/2009 1:33 PM ()

This differs in that &> returns the original object ('x') whereas |> returns the result of the function ('f x'). The &> idiom may be especially useful when you have the create-set-use pattern and you create a mutable object and then do some 'setter' work to mutate it into usable shape - the mutation operations ('f') may return 'unit', whereas you want to continue using the original object. It's almost like an alternative form of mutable 'fluent' interface.

By on 5/29/2009 2:26 PM ()
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