While doing practice, I build a simple function that returns the biggest value in a list:
let rec findMax = // Find maximum value in list
fun l ->
let rec aux =
fun l k ->
match l with
| [] -> k
| x::xs -> if x >= k then aux xs x
else aux xs k
aux l 0
Meanwhile, I built a similar function to find the smallest element in a list:
let finMin = //Find smallest value in list
fun l ->
let rec aux =
fun l k ->
match l with
| [] -> k
| x::xs -> if x <= k then aux xs x
else aux xs k
aux l 0
Here the problem: I initialized both aux functions with k = 0. It is only partially fine: findMax works properly as long as no negative values are in the list. Similarly, findMin works well only with negative numbers.
What should be the proper value to efficiently initialize k? Is there a system-dependant value? Should i previously calculate it? Am I approaching the problem from the wrong side?
P.S. I do not use library functions to find min and max because I am learning the mechanics of the language. Thanks for your patience.
You can take the first item in the list to be the min or max value and then recurse down the rest of the list comparing as you are going. For example:
let myMax items =
match items with
| [] -> failwith "no data"
| head :: tail ->
let rec recMax maxSoFar items =
match items with
| [] -> maxSoFar
| head :: tail ->
if head > maxSoFar then
recMax head tail
else
recMax maxSoFar tail
recMax head tail
It should be System.Int32.MaxValue but also note you should use System.Int32.MinValue for findMax in order to make it work properly with negatives.
Related
I'm trying to find the maximum element in a list without using List.Max for a school assignment using the below given template.
let findMax l =
let rec helper(l,m) = failwith "Not implemented"
match l with
| [] -> failwith "Error -- empty list"
| (x::xs) -> helper(xs,x)
The only solution to the problem I can think of, atm is
let rec max_value1 l =
match l with
|[] -> failwith "Empty List"
|[x] -> x
|(x::y::xs) -> if x<y then max_value1 (y::xs)
else max_value1 (x::xs)
max_value1 [1; 17; 3; 6; 1; 8; 3; 11; 6; 5; 9];;
Is there any way I can go from the function I built to one that uses the template? Thanks!
Your helper function should do the work, the outer function just validates that the list is not empty and if it's not, calls the helper, which should be something like this:
let rec helper (l,m) =
match (l, m) with
| [] , m -> m
| x::xs, m -> helper (xs, max m x)
Note, that you since you're matching against the last argument of the function you can remove it and use function instead of match with:
let rec helper = function
| [] , m -> m
| x::xs, m -> helper (xs, max m x)
let findMax l =
let rec helper(l,m) =
match l with
| [] -> m
| (x::xs) -> helper(xs, if (Some x > m) then Some x else m)
helper (l,None)
Example:
[-2;-6;-1;-9;-56;-3] |> findMax
val it : int option = Some -1
An empty list will return None.
You could go for a tuple to pass both, or simply apply the helper function in your main match (instead of the empty list guard clause). I'm including the answer for someone who might find this question in the future and not have a clear answer.
let findMax l =
let rec walk maxValue = function
| [] -> maxValue
| (x::xs) -> walk (if x > maxValue then x else maxValue) xs
match l with
| [] -> failwith "Empty list"
| (head::tail) -> walk head tail
findMax [1; 12; 3; ] //12
Using fold:
let findMax l = l |> List.fold (fun maxValue x -> if x > maxValue then x else maxValue) (List.head l)
I am not sure of what the exact rules of your assigment are but the max of a list is really just List.reduce max. So
let listMax : int list -> int = List.reduce max
You need the type annotation to please the typechecker.
let inline listMax xs = List.reduce max xs
also works and is generic so it works with e.g. floats and strings as well.
I'm trying to write a tail-recursion function that will look at a list of distinct words, a list of all words, and return a list with the count of occurrences of each word. I'm actually reading the words out of files in a directory, but I can't seem to get the tail-recursion to compile. This is what I have so far:
let countOccurence (word:string) list =
List.filter (fun x -> x.Equals(word)) list
//(all words being a list of all words across several files)
let distinctWords = allWords |> Seq.distinct
let rec wordCloud distinct (all:string list) acc =
match distinct with
| head :: tail -> wordCloud distinct tail Array.append(acc, (countOccurence head all)) //<- What am I doing with my life?
| [] -> 0
I realize this is probably a fairly straightforward question, but I've been banging my head for an hour on this final piece of the puzzle. Any thoughts?
There are several issues with the statement as given:
Use of Array.append to manipulate lists
Typos
Incorrect use of whitespace to group things together
Try expressing the logic as a series of steps instead of putting everything into a single, unreadable line of code. Here's what I did to understand the problems with the above expression:
let rec wordCloud distinct (all:string list) acc =
match distinct with
| head :: tail ->
let count = countOccurence head all
let acc' = acc |> List.append count
wordCloud distinct tail acc'
| [] -> 0
This compiles, but I don't know if it does what you want it to do...
Notice the replacement of Array.append with List.append.
This is still tail recursive, since the call to wordCloud sits in the tail position.
After several hours more work, I came up with this:
let countOccurance (word:string) list =
let count = List.filter (fun x -> word.Equals(x)) list
(word, count.Length)
let distinctWords = allWords |> Seq.distinct |> Seq.toList
let print (tup:string*int) =
match tup with
| (a,b) -> printfn "%A: %A" a b
let rec wordCloud distinct (all:string list) (acc:(string*int) list) =
match distinct with
| [] -> acc
| head :: tail ->
let accumSoFar = acc # [(countOccurance head all)]
wordCloud tail all accumSoFar
let acc = []
let cloud = (wordCloud distinctWords allWords acc)
let rec printTup (tupList:(string*int) list) =
match tupList with
| [] -> 0
| head :: tail ->
printfn "%A" head
printTup tail
printTup cloud
This problem actually has a pretty straightforward solution, if you take a step back and simply type in what you want to do.
/// When you want to make a tag cloud...
let makeTagCloud (words: string list) =
// ...take a list of all words...
words
// ...then walk along the list...
|> List.fold (fun cloud word ->
// ...and check if you've seen that word...
match cloud |> Map.tryFind word with
// ...if you have, bump the count...
| Some count -> cloud |> Map.add word (count+1)
// ...if not, add it to the map...
| None -> cloud |> Map.add word 1) Map.empty
// ...and change the map back into a list when you are done.
|> Map.toList
Reads like poetry ;)
I'm trying to split an F# list into two by taking alternate elements. Here's my attempt:
let split l =
let rec loop l isEven result1 result2 =
match l with
| [] -> result1 result2
| [head::tail] when isEven -> loop tail (not isEven) head::result1 result2
| [head::tail] -> loop tail (not isEven) result1 head::result2
loop l false [] []
That gives me an error:
Program.fs(5,39): error FS0001: Type mismatch. Expecting a
'a
but given a
'b -> 'a list
The resulting type would be infinite when unifying ''a' and ''b -> 'a list'
I don't see how it can be infinite, and I don't understand why it thinks I'm giving it a function from 'b to 'a list. Could somebody tell me where I'm going wrong?
Jack did a good job of explaining what's wrong. Here's an alternate solution that matches two elements at a time. F#'s pattern matching documentation has a lot of great examples.
let split list =
let rec split odd even list =
match list with
| a::b::tail -> split (a::odd) (b::even) tail
| a::tail -> split (a::odd) even tail
| [] -> List.rev odd, List.rev even
split [] [] list
Example output.
printfn "%A" (split [1 .. 10])
System.Console.ReadLine() |> ignore
([1; 3; 5; 7; 9], [2; 4; 6; 8; 10])
Here's a fixed version:
let rec loop l isEven result1 result2 =
match l with
| [] ->
result1, result2
| head :: tail when isEven ->
loop tail (not isEven) (head :: result1) result2
| head :: tail ->
loop tail (not isEven) result1 (head :: result2)
In the first case ([]), I added a comma since the the loop function needs to return the values as a tuple. Without the comma, you're basically treating result1 like a function and applying result2 to it.
The empty list pattern was correct ([]) but in the other cases, you don't use the brackets -- just the cons (::) pattern.
You needed to enclose the head :: result in parenthesis, otherwise F# reads the code as if you wrote this: (loop tail (not isEven) head) :: (result1 result2).
Oh, and if you want the lists you're returning to be in the same order as the original list, you need to use List.rev when you return the lists, like this:
match l with
| [] ->
List.rev result1, List.rev result2
Finally, here's a slightly simplified version of your function -- you don't really need the isEven parameter to make the function work. Instead, you just try to keep the lists the same length:
let rec loop (result1, result2) l =
match l with
| [] ->
List.rev result1, List.rev result2
| hd :: tl ->
if List.length result1 = List.length result2 then
loop (hd :: result1, result2) tl
else
loop (result1, hd :: result2) tl
The simplest solution is not tail recursive but is very comprehensible:
let prepend2 (x, y) (xs, ys) = x::xs, y::ys
let rec split = function
| [] | [_] as xs -> xs, []
| x0::x1::xs -> prepend2 (x0, x1) (split xs)
I have two snippets of code that tries to convert a float list to a Vector3 or Vector2 list. The idea is to take 2/3 elements at a time from the list and combine them as a vector. The end result is a sequence of vectors.
let rec vec3Seq floatList =
seq {
match floatList with
| x::y::z::tail -> yield Vector3(x,y,z)
yield! vec3Seq tail
| [] -> ()
| _ -> failwith "float array not multiple of 3?"
}
let rec vec2Seq floatList =
seq {
match floatList with
| x::y::tail -> yield Vector2(x,y)
yield! vec2Seq tail
| [] -> ()
| _ -> failwith "float array not multiple of 2?"
}
The code looks very similiar and yet there seems to be no way to extract a common portion. Any ideas?
Here's one approach. I'm not sure how much simpler this really is, but it does abstract some of the repeated logic out.
let rec mkSeq (|P|_|) x =
seq {
match x with
| P(p,tail) ->
yield p
yield! mkSeq (|P|_|) tail
| [] -> ()
| _ -> failwith "List length mismatch" }
let vec3Seq =
mkSeq (function
| x::y::z::tail -> Some(Vector3(x,y,z), tail)
| _ -> None)
As Rex commented, if you want this only for two cases, then you probably won't have any problem if you leave the code as it is. However, if you want to extract a common pattern, then you can write a function that splits a list into sub-list of a specified length (2 or 3 or any other number). Once you do that, you'll only use map to turn each list of the specified length into Vector.
The function for splitting list isn't available in the F# library (as far as I can tell), so you'll have to implement it yourself. It can be done roughly like this:
let divideList n list =
// 'acc' - accumulates the resulting sub-lists (reversed order)
// 'tmp' - stores values of the current sub-list (reversed order)
// 'c' - the length of 'tmp' so far
// 'list' - the remaining elements to process
let rec divideListAux acc tmp c list =
match list with
| x::xs when c = n - 1 ->
// we're adding last element to 'tmp',
// so we reverse it and add it to accumulator
divideListAux ((List.rev (x::tmp))::acc) [] 0 xs
| x::xs ->
// add one more value to 'tmp'
divideListAux acc (x::tmp) (c+1) xs
| [] when c = 0 -> List.rev acc // no more elements and empty 'tmp'
| _ -> failwithf "not multiple of %d" n // non-empty 'tmp'
divideListAux [] [] 0 list
Now, you can use this function to implement your two conversions like this:
seq { for [x; y] in floatList |> divideList 2 -> Vector2(x,y) }
seq { for [x; y; z] in floatList |> divideList 3 -> Vector3(x,y,z) }
This will give a warning, because we're using an incomplete pattern that expects that the returned lists will be of length 2 or 3 respectively, but that's correct expectation, so the code will work fine. I'm also using a brief version of sequence expression the -> does the same thing as do yield, but it can be used only in simple cases like this one.
This is simular to kvb's solution but doesn't use a partial active pattern.
let rec listToSeq convert (list:list<_>) =
seq {
if not(List.isEmpty list) then
let list, vec = convert list
yield vec
yield! listToSeq convert list
}
let vec2Seq = listToSeq (function
| x::y::tail -> tail, Vector2(x,y)
| _ -> failwith "float array not multiple of 2?")
let vec3Seq = listToSeq (function
| x::y::z::tail -> tail, Vector3(x,y,z)
| _ -> failwith "float array not multiple of 3?")
Honestly, what you have is pretty much as good as it can get, although you might be able to make a little more compact using this:
// take 3 [1 .. 5] returns ([1; 2; 3], [4; 5])
let rec take count l =
match count, l with
| 0, xs -> [], xs
| n, x::xs -> let res, xs' = take (count - 1) xs in x::res, xs'
| n, [] -> failwith "Index out of range"
// split 3 [1 .. 6] returns [[1;2;3]; [4;5;6]]
let rec split count l =
seq { match take count l with
| xs, ys -> yield xs; if ys <> [] then yield! split count ys }
let vec3Seq l = split 3 l |> Seq.map (fun [x;y;z] -> Vector3(x, y, z))
let vec2Seq l = split 2 l |> Seq.map (fun [x;y] -> Vector2(x, y))
Now the process of breaking up your lists is moved into its own generic "take" and "split" functions, its much easier to map it to your desired type.
I need to generate permutations on a given list. I managed to do it like this
let rec Permute (final, arr) =
if List.length arr > 0 then
for x in arr do
let n_final = final # [x]
let rest = arr |> List.filter (fun a -> not (x = a))
Permute (n_final, rest)
else
printfn "%A" final
let DoPermute lst =
Permute ([], lst)
DoPermute lst
There are obvious issues with this code. For example, list elements must be unique. Also, this is more-less a same approach that I would use when generating straight forward implementation in any other language. Is there any better way to implement this in F#.
Thanks!
Here's the solution I gave in my book F# for Scientists (page 166-167):
let rec distribute e = function
| [] -> [[e]]
| x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
let rec permute = function
| [] -> [[]]
| e::xs -> List.collect (distribute e) (permute xs)
For permutations of small lists, I use the following code:
let distrib e L =
let rec aux pre post =
seq {
match post with
| [] -> yield (L # [e])
| h::t -> yield (List.rev pre # [e] # post)
yield! aux (h::pre) t
}
aux [] L
let rec perms = function
| [] -> Seq.singleton []
| h::t -> Seq.collect (distrib h) (perms t)
It works as follows: the function "distrib" distributes a given element over all positions in a list, example:
distrib 10 [1;2;3] --> [[10;1;2;3];[1;10;2;3];[1;2;10;3];[1;2;3;10]]
The function perms works (recursively) as follows: distribute the head of the list over all permutations of its tail.
The distrib function will get slow for large lists, because it uses the # operator a lot, but for lists of reasonable length (<=10), the code above works fine.
One warning: if your list contains duplicates, the result will contain identical permutations. For example:
perms [1;1;3] = [[1;1;3]; [1;1;3]; [1;3;1]; [1;3;1]; [3;1;1]; [3;1;1]]
The nice thing about this code is that it returns a sequence of permutations, instead of generating them all at once.
Of course, generating permutations with an imperative array-based algorithm will be (much) faster, but this algorithm has served me well in most cases.
Here's another sequence-based version, hopefully more readable than the voted answer.
This version is similar to Jon's version in terms of logic, but uses computation expressions instead of lists. The first function computes all ways to insert an element x in a list l. The second function computes permutations.
You should be able to use this on larger lists (e.g. for brute force searches on all permutations of a set of inputs).
let rec inserts x l =
seq { match l with
| [] -> yield [x]
| y::rest ->
yield x::l
for i in inserts x rest do
yield y::i
}
let rec permutations l =
seq { match l with
| [] -> yield []
| x::rest ->
for p in permutations rest do
yield! inserts x p
}
It depends on what you mean by "better". I'd consider this to be slightly more elegant, but that may be a matter of taste:
(* get the list of possible heads + remaining elements *)
let rec splitList = function
| [x] -> [x,[]]
| x::xs -> (x, xs) :: List.map (fun (y,l) -> y,x::l) (splitList xs)
let rec permutations = function
| [] -> [[]]
| l ->
splitList l
|> List.collect (fun (x,rest) ->
(* permute remaining elements, then prepend head *)
permutations rest |> List.map (fun l -> x::l))
This can handle lists with duplicate elements, though it will result in duplicated permutations.
In the spirit of Cyrl's suggestion, here's a sequence comprehension version
let rec permsOf xs =
match xs with
| [] -> List.toSeq([[]])
| _ -> seq{ for x in xs do
for xs' in permsOf (remove x xs) do
yield (x::xs')}
where remove is a simple function that removes a given element from a list
let rec remove x xs =
match xs with [] -> [] | (x'::xs')-> if x=x' then xs' else x'::(remove x xs')
IMHO the best solution should alleviate the fact that F# is a functional language so imho the solution should be as close to the definition of what we mean as permutation there as possible.
So the permutation is such an instance of list of things where the head of the list is somehow added to the permutation of the rest of the input list.
The erlang solution shows that in a pretty way:
permutations([]) -> [[]];
permutations(L) -> [[H|T] H<- L, T <- permutations( L--[H] ) ].
taken fron the "programming erlang" book
There is a list comprehension operator used, in solution mentioned here by the fellow stackoverflowers there is a helper function which does the similar job
basically I'd vote for the solution without any visible loops etc, just pure function definition
I'm like 11 years late, but still in case anyone needs permutations like I did recently. Here's Array version of permutation func, I believe it's more performant:
[<RequireQualifiedAccess>]
module Array =
let private swap (arr: _[]) i j =
let buf = arr.[i]
arr.[i] <- arr.[j]
arr.[j] <- buf
let permutations arr =
match arr with
| null | [||] -> [||]
| arr ->
let last = arr.Length - 1
let arr = Array.copy arr
let rec perm arr k =
let arr = Array.copy arr
[|
if k = last then
yield arr
else
for i in k .. last do
swap arr k i
yield! perm arr (k + 1)
|]
perm arr 0