Just trying to make a really simple average float list -> float, that finds the average of a list.
This is my code:
let list ls = List.fold (fun acc float -> acc + float) 0.0 ls;;
list [1.60; 2.30; 5.0; 2.30];;
The output is 11.2
I need something added to the function that can divide 11.2 with x elements to find the average.
Any help?
If you want to iterate the list only once you can just count up it's length in parallel (using a tuple `(sum, len)ยด as an accumulator) and then divide afterwards:
let avg xs =
xs
|> List.fold (fun (sum,len) x -> (sum+x,len+1.0)) (0.0,0.0)
|> (fun (sum,len) -> sum / len)
which can be written in a point-free style if you like:
let avg =
List.fold (fun (sum,len) x -> (sum+x,len+1.0)) (0.0,0.0)
>> (fun (sum,len) -> sum / len)
this gives you:
> avg [1.0;2.0;3.0];;
val it : float = 2.0
but of course the easiest way to extent your function is to just get the length of the list and divide by it:
let avg ls =
List.fold (fun acc float -> acc + float) 0.0 ls / (float ls.Length)
for the list this will not make any difference - but you can extend the above version to seqs easily and there it will make a difference (iterate the seq once or twice):
let avg : float seq -> float =
Seq.fold (fun (sum,len) x -> (sum+x,len+1.0)) (0.0,0.0)
>> (fun (sum,len) -> sum / len)
Related
I am currently learning functional programming and F#, and I want to do a loop control until n-2. For example:
Given a list of doubles, find the pairwise average,
e.g. pairwiseAverage [1.0; 2.0; 3.0; 4.0; 5.0] will give [1.5; 2.5; 3.5; 4.5]
After doing some experimenting and searching, I have a few ways to do it:
Method 1:
let pairwiseAverage (data: List<double>) =
[for j in 0 .. data.Length-2 do
yield (data.[j]+data.[j+1])/2.0]
Method 2:
let pairwiseAverage (data: List<double>) =
let averageWithNone acc next =
match acc with
| (_,None) -> ([],Some(next))
| (result,Some prev) -> ((prev+next)/2.0)::result,Some(next))
let resultTuple = List.fold averageWithNone ([],None) data
match resultTuple with
| (x,_) -> List.rev x
Method 3:
let pairwiseAverage (data: List<double>) =
// Get elements from 1 .. n-1
let after = List.tail data
// Get elements from 0 .. n-2
let before =
data |> List.rev
|> List.tail
|> List.rev
List.map2 (fun x y -> (x+y)/2.0) before after
I just like to know if there are other ways to approach this problem. Thank you.
Using only built-ins:
list |> Seq.windowed 2 |> Seq.map Array.average
Seq.windowed n gives you sliding windows of n elements each.
One simple other way is to use Seq.pairwise
something like
list |> Seq.pairwise |> Seq.map (fun (a,b) -> (a+b)/2.0)
The approaches suggested above are appropriate for short windows, like the one in the question. For windows with a length greater than 2 one cannot use pairwise. The answer by hlo generalizes to wider windows and is a clean and fast approach if window length is not too large. For very wide windows the code below runs faster, as it only adds one number and subtracts another one from the value obtained for the previous window. Notice that Seq.map2 (and Seq.map) automatically deal with sequences of different lengths.
let movingAverage (n: int) (xs: float List) =
let init = xs |> (Seq.take n) |> Seq.sum
let additions = Seq.map2 (fun x y -> x - y) (Seq.skip n xs) xs
Seq.fold (fun m x -> ((List.head m) + x)::m) [init] additions
|> List.rev
|> List.map (fun (x: float) -> x/(float n))
xs = [1.0..1000000.0]
movingAverage 1000 xs
// Real: 00:00:00.265, CPU: 00:00:00.265, GC gen0: 10, gen1: 10, gen2: 0
For comparison, the function above performs the calculation above about 60 times faster than the windowed equivalent:
let windowedAverage (n: int) (xs: float List) =
xs
|> Seq.windowed n
|> Seq.map Array.average
|> Seq.toList
windowedAverage 1000 xs
// Real: 00:00:15.634, CPU: 00:00:15.500, GC gen0: 74, gen1: 74, gen2: 71
I tried to eliminate List.rev using foldBack but did not succeed.
A point-free approach:
let pairwiseAverage = List.pairwise >> List.map ((<||) (+) >> (*) 0.5)
Online Demo
Usually not a better way, but another way regardless... ;-]
Let's say I have following equation . My goal is to create sequence which returns next elements of this. Here's my solution and it works:
let rec factorial(n:float) =
match n with
|0.0 -> 1.0
|n -> n * factorial(n-1.0)
let seq1 = Seq.initInfinite( fun i -> factorial(float(i)) / sqrt(float(i)+1.0) ))
Now, analogically, I would like to create sequence which return elements according to equation:
I've got some code, but it's wrong so how to make it work?
let seq2(x:float) = Seq.initInfinite(fun a -> let i = float(a)
(1.0/factorial(0.0)) + System.Math.Pow(x,i)/factorial(i) )
Can't you skip the (1.0/factorial(0.0)) part of the equation (or maybe I misunderstood the question).
edit: i.e
let seq2(x:float) =
Seq.initInfinite(fun a ->
let i = float(a) in
System.Math.Pow(x,i)/factorial(i))
edit: to truncate a seq you can use 'take' and to sum you can use 'sum'. As in
let seq2sum nbelems =
seq2 >> Seq.take nbelems >> Seq.sum
then you get seq2sum 12 3.0 equal to approx 20 :-)
The great thing about functional languages is that you can have your solution be as close an expression of the original definition as possible.
You can avoid explicit type declarations for most functions:
let rec factorial = function
| 0 -> 1
| n -> n * (factorial (n-1))
let e x n =
seq { 0 .. n }
|> Seq.map(fun i -> x ** (float i) / float (factorial i))
|> Seq.sum
In the infinite series, you will have to take the first n entries before you sum, as an infinite series will never finish evaluating:
let e' x n =
Seq.initInfinite(fun i -> x ** (float i) / float (factorial i))
|> Seq.take n
|> Seq.sum
e 1.0 10 //2.718281801
e' 1.0 10 //2.718281801
I'm writing a program that takes a polynomial and returns its derivative. The polynomial is passed as predefined type "poly", which is a list of tuples in which the first element is a float representing a coefficient, and the second is an integer representing the degree of that term. So a poly p = [(2.0, 3);(1.5,2);(3.2;1)] would represent 2x^3 + 1.5x^2 + 3.2x^1. My code is as follows:
let rec diff (p:poly):poly =
match p with
| [] -> raise EmptyList
| [a]-> (fst a * snd a, snd a - 1)
| x::xs -> ((fst x * snd x), (snd x - 1)) :: diff xs
The error I'm getting tells me that the program expects the function to return a type poly, but here has the type 'a * 'b. I don't see why thats the case, when in my base case I return a tuple and in all other situations I'm appending onto an accumulating list. I've played around with the brackets, to no avail. Why is my code tossing this error?
All input is appreciated on the matter.
you said it yourself: in the base case you are returning a tuple not a list - so the inference thinks this is what you want
Just change it into:
let rec diff (p:poly):poly =
match p with
| [] -> raise EmptyList
| [a]-> [fst a * snd a, snd a - 1]
| x::xs -> ((fst x * snd x), (snd x - 1)) :: diff xs
and it should be fine (just replace the (..) with [..] ;) )
remember: :: will cons a new head onto a list
there are a few issues with float vs. int there so I would suggest this (using recursion):
type Poly = (float*int) list
let test : Poly = [(2.0, 3);(1.5,2);(3.2,1);(1.0,0)]
let rec diff (p:Poly):Poly =
match p with
| [] -> []
| x::xs -> (fst x * float (snd x), snd x - 1) :: diff xs
which is really just this:
let diff : Poly -> Poly =
List.map (fun x -> fst x * float (snd x), snd x - 1)
and can look a lot nicer without fst and snd:
let diff : Poly -> Poly =
List.map (fun (a,p) -> a * float p, p - 1)
I have to write a program which give in output a tuple with: min and max of a not-empty list and the value that appears most often.
In particular:
min_max [1;0;-1;2;0;-4] ==> (-4; 2)
min_max: int list -> (int * int)
mode [-1;2;1;2;5;-1;5;5;2] ==> 2
mode: int list -> int
This is the code that I wrote for max (min is almost equal) but how can I do to receive as output a tuple with the two values?
let rec max_list xs =
match xs with
| [] -> failwith "xs" "Empty list"
| [x] -> x
| x1::x2::xs' -> max_list((max2 x1 x2)::xs');;
I'll take the first suggestion from #Mark Seemann's answer and run with it, in order to make it generic, working with any collection type, and handle the case of the empty collection sensibly.
let tryMinMax xs =
Seq.fold (function
| Some(mn, mx) -> fun i -> Some(min mn i, max mx i)
| None -> fun i -> Some(i, i) ) None xs
[1;0;-1;2;0;-4]
|> tryMinMax
// val it : (int * int) option = Some (-4, 2)
For the most frequent part of the question:
let mostFrequent xs =
xs
|> Seq.countBy id
|> Seq.maxBy snd
|> fst
[1;0;-1;2;0;-4]
|> mostFrequent
// val it : int = 0
let minMax xs =
xs
|> List.fold
(fun (mn, mx) i -> min mn i, max mx i)
(System.Int32.MaxValue, System.Int32.MinValue)
Not particularly efficient, but fun to write:
let mode xs =
xs
|> List.groupBy id
|> List.map (fun (i, is) -> i, Seq.length is)
|> List.maxBy snd
|> fst
Option without the use of standard modules:
open System
let tryMinMax xs =
let rec minMax xs mn mx =
match xs with | [] -> mn, mx | h::t -> minMax t (min mn h) (max mx h)
match xs with | [] -> None | _ -> Some(minMax xs Int32.MaxValue Int32.MinValue)
dotnetfiddle
On the second question - show their attempts to solve.
Seq.max finds the max number. I'd like to have something like Seq.findIndex
Seq.maxIndex returns the index of the maximum element.
I believe you are looking for something like:
let maxIndex seq =
fst (Seq.maxBy snd (Seq.mapi (fun i x -> i, x) seq))
Note that giving this function an empty sequence will result in an ArgumentException.
(Alternatively, written in pipelining style:
let maxIndex seq =
seq
|> Seq.mapi (fun i x -> i, x)
|> Seq.maxBy snd
|> fst
)
Why not simply use
let l=[1;2;5;3];;
Seq.findIndex (fun x -> x= Seq.max l) l ;;
?
Or maybe as Johan Kullbom suggest in a comment:
"let m = Seq.max l in Seq.findIndex (fun x -> x = m) l"
if you what a little better O(n)
However, the need to get the index looks to me like a imperative "code smell"
.
In FP it's usually better to use existing functions before you roll your own.
I now this in the eyes of a C programmer seems like a for(i (for(j construct but I bet that you probably really don't need to know the index if you start think in FP.
More or less a duplicate of Finding index of element in a list in Haskell?
PS.
I can't resist.
In Haskell (ghc) the way should probably be something like
let cmpSnd (_, y1) (_, y2) = compare y1 y2
let maxIndex l= fst $ maximumBy cmpSnd $ zip [0..] l
However, since zip in F# doesn't seem to allow zip with unequal lengths of the list(?) the use of mapi is probably the way to go (my haskell version in F#)
let cmpSnd xs= snd xs ;;
let zipIndex a= Seq.mapi (fun i x -> i,x) a;;
let maxIndex seq=fst (Seq.maxBy cmpSnd (zipIndex seq));;
and the reason is only so that I can make a list
let l= [[0;199;1];[4;4];[0;0;399]]
test with makeIndex l;;
and decide that what I really want is a
let cmpSnd' (a,(xs: int list)) = Seq.sum xs;;
let maxIndex' seq=fst (Seq.maxBy cmpSnd' (zipIndex seq));;
Now time to decomposite and make makeIndex take a function
let maxIndexF seq maxF=fst (Seq.maxBy maxF (zipIndex seq));;
val l : int list list = [[1; 2; 199]; [3; 3]; [4; 1]; [0; 299]]
> maxIndexF l cmpSnd'
;;
val it : int = 3
> maxIndexF l cmpSnd
;;
val it : int = 2
Finish it up
let maxIndexF' maxF=fst << Seq.maxBy maxF << zipIndex ;;
maxIndexF' cmpSnd' l;;
maxIndexF' cmpSnd l;;