I have an obj[,] whose components are all floats. I want to convert it to a float[,]. I tried many permutations of box, unbox, Array2D.map float, Array2D.copy, System.Convert.ChangeType, etc and none seem to work. How to proceed?
This seems to work just fine for me:
let boxedArray = Array2D.init 2 2 (fun x y -> box (float (x + y)))
let unboxedArray = boxedArray |> Array2D.map unbox<float>
printfn "%A" (boxedArray.GetType()) // System.Object[,]
printfn "%A" (unboxedArray.GetType()) // System.Double[,]
Related
In Reason (and OCaml), there is a non-traditional way of passing arguments using the |> operator. What is the convention for when it should be used? I am currently using it all over the place just because of how novel I find it.
Using |> (forward pipe) is helpful for showing the order of executions.
For example, if you want to execute function f, then g like this:
g(f(x))
It's easier to see the order of executions (e.g., f and then g) this way:
x |> f |> g
Programming languages like OCaml or F# are used a lot to transform data from one form to another, so |> can be used that way to show how data got transformed.
let sqr = x => x * x;
[1,2,3]
|> List.map (x => x + 1)
|> List.map (sqr);
The reverse application operator (|>) can simply be defined as
let (|>) x f = f x
This infix operator takes a value x and a function f and apply the latter to the first (f x). This may not seem apparently useful at first, but the operator is powerful when used correctly because functions in Ocaml are curried.
For example, let's say we had a function wackymath: int -> int -> int -> int
let wackymath a b c = a + b - c
The type of wackymath is int -> int -> int -> int. This is because in a functional realm (specifically, lambda calculus), any function only applies to one argument at a time. Therefore, with the help of parentheses, the order of application of wackymath looks like this:
(((wackymath a) b) c)
Argument substitution could make this clearer.
let f1 = wackymath 10;; (* 10 + b - c *)
let f2 = f1 19;; (* 10 + 19 - c *)
f2 4;; (* 10 + 19 - 4 = 25 *)
This could be expressed with the |> operator as such:
4 |> (19 |> (10 |> wackymath));;
Now it's clear why it's called reverse application operator. The parentheses are there because |> is left-associative. Saying |> helps avoid parentheses are not exactly precise in all cases.
Usually the operator is useful in situations when you want to compose a series of sequential function applications
[1; 2; 3; 4; 5]
|> List.map (fun x -> x * 2)
|> List.filter (fun x -> x < 3)
|> fun l -> match l with
| [] -> 0
| l' -> l' |> List.fold_left ~init:0 ~f:(fun a b -> a + b)
;;
I would like to log (print for now) all the elements in results before reducing it for return. Is there a way to achieve that?
let calculate ~size_of_experiment:s ~number_of_buckets:n =
let results = run_experiments s n in
List.iter (fun x -> print_endline x) results;
List.fold_left (fun x y -> x + (snd y)) 0 results
The code above does not compile:
Error: This expression has type (int * int) list
but an expression was expected of type string list
Type int * int is not compatible with type string
Your only problem seems to be that elements of the list are of type (int * int) and you are treating them as strings.
let string_of_int_pair (a, b) = Printf.sprintf "(%d, %d)" a b
let calculate ~size_of_experiment:s ~number_of_buckets:n =
let results = run_experiments s n in
List.iter (fun x -> print_endline (string_of_int_pair x)) results;
List.fold_left (fun x y -> x + (snd y)) 0 results
The more general problem is that it would be really nice to have a way to print values of various types without writing the code yourself for each case. For that you can use something like deriving.
I'm having a problem with understanding how F# works. I come from C# and I think that I'm trying to make F# work like C#. My biggest problem is returning values in the correct format.
Example:
Let's say I have function that takes a list of integers and an integer.
Function should print a list of indexes where values from list match passed integer.
My code:
let indeks myList n = myList |> List.mapi (fun i x -> if x=n then i else 0);;
indeks [0..4] 3;;
However it returns:
val it : int list = [0; 0; 0; 3; 0]
instead of just [3] as I cannot ommit else in that statement.
Also I have targeted signature of -> int list -> int -> int list and I get something else.
Same goes for problem no. 2 where I want to provide an integer and print every number from 0 to this integer n times (where n is the iterated value):
example:
MultiplyValues 3;;
output: [1;2;2;3;3;3]
Best I could do was to create list of lists.
What am I missing when returning elements?
How do I add nothing to the return
example: if x=n then n else AddNothingToTheReturn
Use List.choose:
let indeks lst n =
lst
|> List.mapi (fun i s -> if s = n then Some i else None)
|> List.choose id
Sorry, I didn't notice that you had a second problem too. For that you can use List.collect:
let f (n : int) : list<int> =
[1 .. n]
|> List.collect (fun s -> List.init s (fun t -> s))
printfn "%A" (f 3) // [1; 2; 2; 3; 3; 3]
Please read the documentation for List.collect for more information.
EDIT
Following s952163's lead, here is another version of the first solution without the Option type:
let indeks (lst : list<int>) (n : int) : list<int> =
lst
|> List.fold (fun (s, t) u -> s + 1, (if u = n then (s :: t) else t)) (0, [])
|> (snd >> List.rev)
This one traverses the original list once, and the (potentially much shorter) newly formed list once.
The previous answer is quite idiomatic. Here's one solution that avoids the use of Option types and id:
let indeks2 lst n =
lst
|> List.mapi (fun i x -> (i,x))
|> List.filter (fun x -> (fst x) % n = 0 )
|> List.map snd
You can modify the filter function to match your needs.
If you plan to generate lots of sequences it might be a good idea to explore Sequence (list) comprehensions:
[for i in 1..10 do
yield! List.replicate i i]
If statements are an expression in F# and they return a value. In this case both the IF and ELSE branch must return the same type of value. Using Some/None (Option type) gets around this. There are some cases where you can get away with just using If.
Very often when writing generic code in F# I come by a situation similar to this (I know this is quite inefficient, just for demonstration purposes):
let isPrime n =
let sq = n |> float |> sqrt |> int
{2..sq} |> Seq.forall (fun d -> n % d <> 0)
For many problems I can use statically resolved types and get even a performance boost due to inlining.
let inline isPrime (n:^a) =
let two = LanguagePrimitives.GenericOne + LanguagePrimitives.GenericOne
let sq = n |> float |> sqrt |> int
{two..sq} |> Seq.forall (fun d -> n % d <> LanguagePrimitives.GenericZero)
The code above won't compile because of the upper sequence limit being a float. Nongenerically, I could just cast back to int for example.
But the compiler won't let me use any of these:
let sq = n |> float |> sqrt :> ^a
let sq = n |> float |> sqrt :?> ^a
and these two lead to a InvalidCastException:
let sq = n |> float |> sqrt |> box |> :?> ^a
let sq = n |> float |> sqrt |> box |> unbox
Also, upcast and downcast are forbidden.
let sq = System.Convert.ChangeType(n |> float |> sqrt, n.GetType()) :?> ^a works, but seems very cumbersome to me.
Is there a way that I overlooked or do I really have to use the last version? Because the last one will also break for bigint, which I need quite often.
With the trick from FsControl, we can define generic function fromFloat:
open FsControl.Core
type FromFloat = FromFloat with
static member instance (FromFloat, _:int32 ) = fun (x:float) -> int x
static member instance (FromFloat, _:int64 ) = fun (x:float) -> int64 x
static member instance (FromFloat, _:bigint ) = fun (x:float) -> bigint x
let inline fromFloat (x:float):^a = Inline.instance FromFloat x
let inline isPrime (n:^a) =
let two = LanguagePrimitives.GenericOne + LanguagePrimitives.GenericOne
let sq = n |> float |> sqrt |> fromFloat
{two..sq} |> Seq.forall (fun d -> n % d <> LanguagePrimitives.GenericZero)
printfn "%A" <| isPrime 71
printfn "%A" <| isPrime 6L
printfn "%A" <| isPrime 23I
Inline.instance was defined here.
here's my code: (should work fine)
let rec interleave = function
| ([],ys) -> []
| (xs,[]) -> []
| (x::xs,y::ys) -> x :: y :: interleave (xs, ys)
let gencut n list =
let first = list |> Seq.take n |> Seq.toList
let last = list |> Seq.skip n |> Seq.toList
(first, last)
let cut list = gencut ((List.length list)/2) list
let shuffle x = interleave (cut x)
let isNotSame (list1, list2) = if list1 = list2 then false else true
let countShuffles xs =
let mutable newList = xs
let mutable x = 1
if (List.length(xs) > 1) then newList <- shuffle newList
while isNotSame (newList, xs) do
newList <- shuffle newList
x <- x + 1
x
//lists countShuffles from 1 to x
let listShuffles x =
for i = 1 to x/2 do
let y = [1..(i*2)]
let z = countShuffles y
printf "A deck of %d cards takes %d shuffles\n" (i*2) z
printf ""
The flow is (from main function down to 1st helper):
listShuffles -> countShuffles -> shuffle + isNotSame -> cut -> gencut + interleave
(so just try listShuffles)
What "countShuffles" does is:
take an int, creates a list, (1..n), (which is supposed to represent a deck of cards),
cuts it in half, does a perfect-out shuffle (perfect bridge shuffle)
and counts how many shuffles it takes to make the deck original again
What listShuffles does is:
takes an int, and prints out countShuffles 1 through n
(you need an even amount of cards in the deck)
Sorry about the explanation, now my question:
is it possible to see how many times a certain number is returned?
i.e.:
listShuffles 10000;;
see how many times "16" appeared.
i was thinking of making a list.
and incrementing a given index.
which represents a certain number that was returned.
but i cant find how to do that...
p.s. i dont care how my code is wrong or anything like that,
this is my first F# program, and it is homework based on my professor's criteria,
(the assignment is complete, this question is for curiosity)
There are a few alternatives
If you only want one number you can do
List |> Seq.sumBy (fun t -> if t = 16 then 1 else 0)
If you want a range of different numbers, it may be better to do
let map = List |> Seq.countBy (fun t -> t) |> Map.ofSeq
then map.[16] is the number of times that 16 occurs in the list
You can do something like:
let listShuffles x =
[| for i = 1 to x/2 do
yield countShuffles [1..(i*2)] |]
Now this function return array and then you can use Array module functions to find how many times a number appears
listShuffles 1000 |> Array.filter ((=) 16) |> Array.length
Or to print all such numbers and their occurrence count:
listShuffles 100
|> Array.toSeq |> Seq.groupBy id
|> Seq.iter (fun (k,v) -> printfn "%d appears %d times" k (v.Count()))