Marcom
Marcom

Reputation: 4741

F# Print if true

I'm trying to print the output of function only when it is true but so far all attempts have been unsuccsessful.

Something on the lines of:

let printFactor a b =  if b then print_any((a,b)) 

Where b is a boolean and a is an integer. When I try it I get:

val printFactor : 'a -> bool -> unit

Any suggestions?

EDIT:

To put things in context im trying to use this with a pipe operator. Lets say I have a function xyz that outputs a list of (int, bool). Id like to do something on these lines:

xyz |> printFactor

to print the true values only.

Upvotes: 3

Views: 1238

Answers (1)

Brian
Brian

Reputation: 118895

You could do e.g. this

let xyz() = [ (1,true); (2,false) ]

let printFactor (i,b) = 
    if b then
        printfn "%A" i

xyz() |> List.iter printFactor

but it would probably be more idiomatic to do, e.g. this

xyz() 
|> List.filter (fun (i,b) -> b) 
|> List.iter (fun (i,b) -> printfn "%d" i)

that is, first filter, and then print.

Upvotes: 6

Related Questions