Indeed, what appears to be a variable name on the left of a let is actually a pattern. So you can deconstruct a tuple, for example:

1
let a, b = 3, 4

or even nested tuples:

1
let a, (b, c) = 3, (4, 5)

In your case, given that you're taking the first four elements off a list you should use a pattern match with a catch-all for the eventuality of a list with <4 elements:

1
2
3
let r0, r1, r2, r3 = match list with
  | r0::r1::r2::r3::_ -> r0, r1, r2, r3
  | _ -> invalid_arg "My list"

However, you may want to replace your use of a list with a 4-tuple but I can't tell without more context.

Cheers,
Jon.

By on 11/30/2006 2:28 PM ()

Thanks you your comments chaps.

I realize this can all be done using a match expression. I was thinking that since this is essentially a pattern match, is there, or could there be, a special catch all clause in let bindings. It's all a case of reducing typing (but also avoiding all warnings). Without it, at least for lists (which I use alot because I like recursion), I'd write the List.nth version simply because with a bit of copy&paste its the shortest to type if not the most elegant.

Cheers,

Andy

By on 11/30/2006 4:04 PM ()

And do you know, is there a way to do something like that:

1
let rec myFunction (hA::tA) (hB::tB) = hA+hB + (myFunction tA tB)

This example works, but I want to have a pattern for empty list, and I can't find information about whis construction.

I tried to use function keyword:

1
2
3
4
5
let rec pair =
    function | ((f:float->float->float),(hx::tx:float list),(hw::tw:float list),acc) -> pair (f,tx,tw,(acc + (f hx hw)))
             | ((f:float->float->float),[],[],acc) -> acc
             | ((f:float->float->float),_,[],acc) -> failwith "Lists length are not equal!"
             | ((f:float->float->float),[],_,acc) -> failwith "Lists length are not equal!"

But here I am to use a tuple, that doesn't suits me.

By on 10/2/2008 2:39 AM ()

Hi,

You can use the match keyword, instead.

1
2
3
4
5
let rec pair f a b acc =
  match a, b with
  | [], [] -> acc
  | ha::ta, hb::tb -> pair f ta tb (acc + f ha hb)
  | _ -> failwith "Lists length are not equal!"

If I understand correctly, you can also use library functions:

1
let pair f a b = List.map2 f a b |> List.sum

Laurent

By on 10/2/2008 4:57 AM ()

Thank you for your reply!

I know about match keyword, but this Prolog-style function definition seems to me more elegant.

I liked your solution of your problem very much! :)

By on 10/2/2008 7:48 AM ()

Maybe :

1
2
3
4
5
6
7
 

let [r0;r1;r2;r3] = 
    match r with 
    | a::b::c::d::e::_ ->  a::b::c::d::e::[]
    | _ -> 0::0::0::0::0::[] 
By on 11/29/2006 11:19 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