F# function calling syntax confusion -
i have piece of code:
links |> seq.map (fun x -> x.getattributevalue ("href", "no url"))
which wanted rewrite to:
links |> seq.map (fun x -> (x.getattributevalue "href" "no url"))
but f# compiler doesn't seem that. under impression these 2 function calls interchangeable:
f (a, b) (f b)
the error is:
the member or object constructor 'getattributevalue' taking 2 arguments not accessible code location. accessible versions of method 'getattributevalue' take 2 arguments.
which seems amusing, seems indicate needs i'm giving it. missing here?
a usual function call in f# written without parentheses , parameters separated spaces. simple way define function of several parameters write this:
let add b = + b
as pascal noted, way of specifying parameters called currying - idea function takes single parameter , result function takes second parameter , returns actual result (or function). when calling simple function one, write add 10 5
, compiler (in principle) interprets ((add 10) 5)
. has nice advantages - example allows use partial function application specify first few arguments of function:
let addten = add 10 // declares function adds 10 argument addten 5 // returns 15 addten 9 // returns 19
this feature practically useful example when processing lists:
// code using explicit lambda functions.. [ 1 .. 10 ] |> list.map (fun x -> add 10 x) // can rewritten using partial function application: [ 1 .. 10 ] |> list.map (add 10)
now, let's confusing part - in f#, can work tuples, simple data types allow group multiple values single values (note tuples aren't related functions in way). can example write:
let tup = (10, "ten") // creating tuple let (n, s) = tup // extracting elements of tuple using pattern printfn "n=%d s=%s" n s // prints "n=10 s=ten"
when write function takes parameters in parentheses separated comma, you're writing function takes single parameter tuple:
// following function: let add (a, b) = * b // ...means same thing as: let add tup = let (a, b) = tup // extract elements of tuple * b // can call function creating tuple inline: add (10, 5) // .. or creating tuple in advance let t = (10, 5) add t
this function of different type - takes single parameter tuple, while first version function took 2 parameters (using currying).
in f#, situation bit more complicated - .net methods appear methods take tuple parameter (so can call them parenthesized notation), limited (e.g. cannot create tuple first , call method giving tuple). also, compiled f# code doesn't produce methods in curried form (so cannot use partial function application directly c#). due performance reasons - of times, specify arguments , can implemented more efficiently.
however, principle function either takes multiple parameters or takes tuple parameter.
Comments
Post a Comment