Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do in F# what would be called compression in APL?

Tags:

f#

apl

In APL one can use a bit vector to select out elements of another vector; this is called compression. For example 1 0 1/3 5 7 would yield 3 7.

Is there a accepted term for this in functional programming in general and F# in particular?

Here is my F# program:

let list1 = [|"Bob"; "Mary"; "Sue"|]
let list2 = [|1; 0; 1|]

[<EntryPoint>]
let main argv = 

    0 // return an integer exit code

What I would like to do is compute a new string[] which would be [|"Bob"; Sue"|]

How would one do this in F#?

like image 618
JonnyBoats Avatar asked Mar 30 '14 09:03

JonnyBoats


Video Answer


1 Answers

Array.zip list1 list2                 // [|("Bob",1); ("Mary",0); ("Sue",1)|]
|> Array.filter (fun (_,x) -> x = 1)  // [|("Bob", 1); ("Sue", 1)|]
|> Array.map fst                      // [|"Bob"; "Sue"|]

The pipe operator |> does function application syntactically reversed, i.e., x |> f is equivalent to f x. As mentioned in another answer, replace Array with Seq to avoid the construction of intermediate arrays.

I expect you'll find many APL primitives missing from F#. For lists and sequences, many can be constructed by stringing together primitives from the Seq, Array, or List modules, like the above. For reference, here is an overview of the Seq module.

like image 156
Søren Debois Avatar answered Oct 07 '22 02:10

Søren Debois