Alex 75
Alex 75

Reputation: 3266

F# Functions (forward pipe operator) does not work with arrays?

I have a complex example but I reduced the case using simple obejcts.

Given 2 functions:

let add (a:int)   b = a     + b
let aee (a:int[]) b = a.[0] + b 

them can be used in this way:

let c = add 1 5 

let a = [|1; 2|]
let d = aee a 5

So, why this is valid:

let c = 1 |> add 5

and this is not ?

let d = [|1;2|] |> aee 5  // Type mismatch, expecting int[] -> `a but given int -> int

My real scenario, in case it matters, is the following:

open FSUnit

type Tick (symbol:string, ask:decimal, bid:decimal) =
    member __.Symbol = symbol
    member __.Ask = ask
    member __.Bid = bid

let containSymbol (ticks:Tick[]) symbol =
    ( ticks |> Array.tryFind (fun t -> t.Symbol = symbol) ).IsSome


let ticks = [| Tick("aaa", 1m, 2m) |]

// I'm able to do these
should be True <| containSymbol ticks "aaa" 
containSymbol ticks "aaa" |> should be True

// but not this
ticks |> containSymbol CurrencyPair.XRP_BTC |> should be True  // does not work as described in the small example
// or (desiderable) this
ticks |> should contain (fun t -> t.symbol = "aaa")           // don't know how to create/pass a ContainwsConstraint with a function 

Yes, the final goal is to be able to use ticks |> should contain (fun t -> t.symbol = "aaa") but I'm going with the first little step...

Upvotes: 2

Views: 110

Answers (1)

JLRishe
JLRishe

Reputation: 101778

The pipe operator allows you to pass an argument into a function which may or may not have been partially evaluated. The value being piped in is passed as the next argument to that function.

In this example:

let d = [|1;2|] |> aee 5 

You are partially evaluating aee with the argument 5, and then passing in the argument [|1;2|] after that, using the pipe operator, but this does not work, because the first parameter of aee is an array, not an integer.

In order for this to work the way you are trying it, you need to change the order of the parameters:

let aee b (a:int[]) = a.[0] + b 
let d = [|1;2|] |> aee 5

Upvotes: 5

Related Questions