Print list of tuple F# - f#

I have some code I am trying to test, that is supposed to merge two int lists of same length into a tuple list. I have got it to compile but I cannot find out if it works as I am having trouble printing the result.
Here is what I have so far:
let myList = [5;15;20;25;30;200]
let myList2 = [6;16;21;26;31;201]
let rec tupleMaker (list1: int list) (list2: int list) =
match list1, list2 with
| (h1 :: tail1),(h2 :: tail2)->
let (a,b) = (h1,h2)
(a,b) :: tupleMaker tail1 tail2
| _,_->
[]
let z = tupleMaker myList, myList2
//printfn z
//printfn %A
The printfn does not work and neither has anything else I tried, any help would be greatly appreciated.

You just implemented List.zip:
List.zip myList myList2
//val it : (int * int) list =
// [(5, 6); (15, 16); (20, 21); (25, 26); (30, 31); (200, 201)]

Note: The OP has not been seen in months so this answer will probably never get an accept vote. Don't let that stop you from thinking it is not a correct answer.
First to generate a list of tuples.
This uses two different types of list to make the answer more useful in general.
let myList: int list = [1;2;3]
let myList2 : string list = ["a";"b";"c"]
let listOfTuple:(int * string) list = List.zip myList myList2
There are many ways to print a list of tuples, but the basic idea is to use List.iter to access the individual tuples in the list and then apply standard means to access the items in the tuple.
Example 1:
This doesn't use List.iter. It uses just printfn %A. This is useful when you are stuck trying to figure out why something will not print and just need to see the data as the system sees it.
printfn "%A" listOfTuple
Result:
[(1, "a"); (2, "b"); (3, "c")]
Example 2:
This uses List.iter with printfn %A. This is useful when you know the data is a list but don't know the type of the individual items.
listOfTuple |>
List.iter (printfn "%A")
Result:
(1, "a")
(2, "b")
(3, "c")
Example 3:
This uses List.iter with a tuple deconstructor, e.g. let (a,b) = values, to get at the individual values of the tuple. This is useful if you want to print every value of every item in the list.
listOfTuple |>
List.iter(
fun values ->
let (a,b) = values
printfn ("%i, %s") a b
)
Result:
1, a
2, b
3, c
Example 4:
This uses List.iter with a match statement to get at the individual values of the tuple. This is useful if you want to do more complicated processing, such as filtering before printing, or having different printing messages and/or formats for different values.
listOfTuple |>
List.iter(
fun values ->
match values with
| (a,_) when a > 1 ->
printfn ("%i") a
| (_,_) -> ()
)
Result
2
3

Related

Equivalent of repeated takeWhile calls: does this function have a "standard" name?

I have a scenario where the standard List.groupBy function isn't what I want, but I don't know the right name for this function so it's making it hard to search for.
I have a list of items of type 'T, and a 'T -> 'k key-producing function. The items are already somewhat "grouped" together in the list, so that when you map the list through the key function, its result will tend have the same key in a row several times, e.g. [1; 1; 1; 2; 2; 1; 1; 3; 3; 3; 1; 1]. What I want is to get a list of lists, where the inner list contains all the items for which the key-producing function returned the same value -- but it should NOT group the different sequences of 1's together.
In other words, say my data was a list of strings, and the key-producing function was String.length. So the input is:
["a"; "e"; "i"; "to"; "of"; "o"; "u"; "and"; "for"; "the"; "I"; "O"]
The output I'm looking for would be:
[["a"; "e"; "i"]; ["to"; "of"]; ["o"; "u"]; ["and"; "for"; "the"]; ["I"; "O"]]
To think of it another way: this is like taking the first item of the list and storing the result of calling the key function. Then you'd use takeWhile (fun x -> keyFun x = origKeyFunResult) to generate the first segment. Then when that takeWhile stops returning values, you record when it stopped, and the value of keyFun x on the first value that didn't return the original result -- and go on from there. (Except that that would be O(N*M) where M is the number of sequences, and would devolve into O(N^2) in many cases -- whereas it should be possible to implement this function in O(N) time).
Now, I can write that function pretty easily. That's not the question. What I want to know is whether there's a standard name for this function. Because I thought it would be called groupBy, but that's something else. (List.groupBy String.length would return [(1, ["a"; "e"; "i"; "o"; "u"; "I"; "O"]); (2, ["to"; "of"]), (3, ["and"; "for"; "the"])], but what I want in this case is for the "a/e/i", "o/u", and "I/O" lists to remain separated, and I don't want the value that the key-generating returns to be in the output data).
Maybe there isn't a standard name for this function. But if there is, what is it?
I'm a little late and it seems that you have found a solution, and it seems that there doesn't exists a single function i F# that can handle the problem.
Just for the challenge I tried to find some usable solutions and came up with the following (whether they are efficient or not is up the reader to deside):
open System
module List =
/// <summary>
/// Generic List Extension:
/// Given a comparer function the list will be chunked into sub lists
/// starting when ever comparer finds a difference.
/// </summary>
let chunkByPredicate (comparer : 'T -> 'T -> bool) list =
let rec func (i : int, lst : 'T list) : 'T list list =
if i >= lst.Length then
List.empty
else
let first = lst.[i]
let chunk = lst |> List.skip(i) |> List.takeWhile (fun s -> comparer first s)
List.append [chunk] (func((i + chunk.Length), lst))
func (0, list) |> List.where (fun lst -> not (List.isEmpty lst))
// 1. Using List.fold to chunk by string length
let usingListFold (data : string list) =
printfn "1. Using List.fold: "
data
|> List.fold (fun (acc : string list list) s ->
if acc.Length > 0 then
let last = acc.[acc.Length - 1]
let lastLength = last.[0].Length
if lastLength = s.Length then
List.append (acc |> List.take (acc.Length - 1)) [(last |> List.append [s])]
else
List.append acc [[s]]
else
[[s]]) ([])
|> List.iter (printfn "%A")
printfn ""
// 2. Using List.chunkByPredicate
let usingListChunkByPredicate<'a> (predicate : 'a -> 'a -> bool, data : 'a list) =
printfn "2. Using List.chunkByPredicate: "
data
|> List.chunkByPredicate predicate
|> List.iter (printfn "%A")
printfn ""
[<EntryPoint>]
let main argv =
let data = ["a"; "e"; "i"; "to"; "of"; "o"; "u"; "and"; "for"; "the"; "I"; "O"]
usingListFold data
usingListChunkByPredicate<string>((fun first s -> first.Length = s.Length), data)
let intData = [0..50]
usingListChunkByPredicate<int>((fun first n -> first / 10 = n / 10), intData)
Console.ReadLine() |> ignore
0

Reformatting list based on a condition in F#

I'm new to functional programming and am working on a project in F#.
I've run a problem: I have a list of type string list list and I need to build separate lists based on the middle element of each string list. For example:
[["1";"b";"2"];["2";"a";"0"];["3";"b";"4"];["3";"a";"5"]]
Would be broken into 2 lists similar to the following:
let a = [["2";"0"];["3";"5"]]
let b = [["1";"2"];["3";"4"]]
I tried to use let a = [for [x;y;z] in myList do yield [x;z]] but am having trouble adding in the condition of y = "b", for instance.
Any help would be greatly appreciated
let myList = [["1";"b";"2"];["2";"a";"0"];["3";"b";"4"];["3";"a";"5"]]
let a = [for [x;y;z] in myList do if y="a" then yield [x;z]]
let b = [for [x;y;z] in myList do if y="b" then yield [x;z]]
You're trying to split a list by its middle element. What is the expected behaviour when your list does not have 3 elements?
In the answer provided by Functional_S, you'll see the wiggly lines under the [x;y;z] in
let a = [for [x;y;z] in myList do if y="a" then yield [x;z]]
The compiler says "Incomplete pattern matches". Rather than now adding extra checks to handle empty lists, lists of length 2, etc, consider changing the design of your data types. If you have data that always contains of 3 elements, then use a data structure that has exactly 3 elements. Tuples are an obvious choice here, or use a record.
let myList = [ ("1","b","2"); ("2","a","0"); ("3","b","4"); ("3","a","5") ]
let splitByMiddle =
myList
|> List.groupBy (fun (_, middle, _) -> middle)
|> List.map (fun (middle, elems) -> middle, elems |> List.map (fun (l, _, r) -> l, r))
If you execute that in interactive, you'll get:
val splitByMiddle : (string * (string * string) list) list =
[("b", [("1", "2"); ("3", "4")]); ("a", [("2", "0"); ("3", "5")])]
An alternative would be:
let splitByMiddle =
myList
|> List.map (fun (l, middle, r) -> middle, (l, r))
|> List.groupBy fst
|> List.map (fun (middle, elems) -> middle, elems |> List.map snd)
I find that F# is really at its peak performance when you model your domain as closely as possible with your datatypes. In languages like Matlab, vectors and matrics are your number one work horse, you'd put everything into lists. But in F#, defining data types comes so cheaply (in terms of typing effort) - and once you've done so, the compiler is your best friend to remind you of possible corner cases your code is not covering.
In that light: I see all your middle elements are string, whereas the left/right elements are integers. Maybe your domain is better modelled by this record?
type R =
{
Left: int
Right: int
Middle: string
}
let create (l, m, r) = { Left = l; Right = r; Middle = m}
let myList = [ create(1,"b",2); create(2,"a",0); create(3,"b",4); create(3,"a",5) ]
let splitByMiddle =
myList
|> List.groupBy (fun r -> r.Middle)
This will give you:
val splitByMiddle : (string * R list) list =
[("b", [{Left = 1;
Middle = "b";
Right = 2;}; {Left = 3;
Middle = "b";
Right = 4;}]); ("a", [{Left = 2;
Middle = "a";
Right = 0;}; {Left = 3;
Middle = "a";
Right = 5;}])]

Extract elements from sequences, tuples

Say I have this:
let coor = seq { ... }
// val coor : seq<int * int> = seq[(12,34); (56, 78); (90, 12); ...]
I'm trying to get the value of the first number of the second element in the sequence, in this case 56. Looking at the MSDN Collection API reference, Seq.nth 1 coor returns (56, 78), of type seq <int * int>. How do I get 56 out of it?
I suggest you go through Tuple article:
http://msdn.microsoft.com/en-us/library/dd233200.aspx
A couple of exceptions that might shed some light on the problem:
Function fst is used to access the first element of the tuple:
(1, 2) |> fst // returns 1
Function snd is used to access the second element
(1, 2) |> snd // returns 2
In order to extract element from wider tuples you can use following syntax:
let _,_,a,_ = (1, 2, 3, 4) // a = 3
To use it in various collections (well lambdas that are passed to collection's functions), let's start with following sequence:
let s = seq {
for i in 1..3 do yield i,-i
}
We end up with
seq<int * int> = seq [(1, -1); (2, -2); (3, -3)]
Let's say we want to extract only the first element (note the arguments of the lambda):
s |> Seq.map (fun (a, b) -> a)
Or even shorter:
s |> Seq.map fst
And lets finally go back to your question.
s |> Seq.nth 1 |> fst
It's a tuple, so you could use the function fst;
> let value = fst(Seq.nth 1 coor);;
val value : int = 56
...or access it via pattern matching;
> let value,_ = Seq.nth 1 coor;;
val value : int = 56

F# return element pairs in list

I have been looking for an elegant way to write a function that takes a list of elements and returns a list of tuples with all the possible pairs of distinct elements, not taking into account order, i.e. (a,b) and (b,a) should be considered the same and only one of them be returned.
I am sure this is a pretty standard algorithm, and it's probably an example from the cover page of the F# documentation, but I can't find it, not even searching the Internet for SML or Caml. What I have come up with is the following:
let test = [1;2;3;4;5;6]
let rec pairs l =
seq {
match l with
| h::t ->
yield! t |> Seq.map (fun elem -> (h, elem))
yield! t |> pairs
| _ -> ()
}
test |> pairs |> Seq.toList |> printfn "%A"
This works and returns the expected result [(1, 2); (1, 3); (1, 4); (1, 5); (1, 6); (2, 3); (2, 4); (2, 5); (2, 6); (3, 4); (3, 5); (3, 6); (4, 5); (4, 6); (5, 6)] but it looks horribly unidiomatic.
I should not need to go through the sequence expression and then convert back into a list, there must be an equivalent solution only involving basic list operations or library calls...
Edited:
I also have this one here
let test = [1;2;3;4;5;6]
let rec pairs2 l =
let rec p h t =
match t with
| hx::tx -> (h, hx)::p h tx
| _ -> []
match l with
| h::t -> p h t # pairs2 t
| _ -> []
test |> pairs2 |> Seq.toList |> printfn "%A"
Also working, but like the first one it seems unnecessarily involved and complicated, given the rather easy problem. I guess my question is mor about style, really, and if someone can come up with a two-liner for this.
I think that your code is actually pretty close to an idiomatic version. The only change I would do is that I would use for in a sequence expression instead of using yield! in conjunction with Seq.map. I also usually format code differently (but that's just a personal preference), so I would write this:
let rec pairs l = seq {
match l with
| h::t -> for e in t do yield h, elem
yield! pairs t
| _ -> () }
This is practically the same thing as what Brian posted. If you wanted to get a list as the result then you could just wrap the whole thing in [ ... ] instead of seq { ... }.
However, this isn't actually all that different - under the cover, the compiler uses a sequence anyway and it just adds conversion to a list. I think that it may be actually a good idea to use sequences until you actually need a list (because sequences are evaluated lazilly, so you may avoid evaluating unnecessary things).
If you wanted to make this a bit simpler by abstracting a part of the behavior into a separate (generally useful) function, then you could write a function e.g. splits that returns all elements of a list together with the rest of the list:
let splits list =
let rec splitsAux acc list =
match list with
| x::xs -> splitsAux ((x, xs)::acc) xs
| _ -> acc |> List.rev
splitsAux [] list
For example splits [ 1 .. 3 ] would give [(1, [2; 3]); (2, [3]); (3, [])]. When you have this function, implementing your original problem becomes much easier - you can just write:
[ for x, xs in splits [ 1 .. 5] do
for y in xs do yield x, y ]
As a guide for googling - the problem is called finding all 2-element combinations from the given set.
Here's one way:
let rec pairs l =
match l with
| [] | [_] -> []
| h :: t ->
[for x in t do
yield h,x
yield! pairs t]
let test = [1;2;3;4;5;6]
printfn "%A" (pairs test)
You seem to be overcomplicating things a lot. Why even use a seq if you want a list? How about
let rec pairs lst =
match lst with
| [] -> []
| h::t -> List.map (fun elem -> (h, elem)) t # pairs t
let _ =
let test = [1;2;3;4;5;6]
printfn "%A" (pairs test)

Return value in F# - incomplete construct

I've trying to learn F#. I'm a complete beginner, so this might be a walkover for you guys :)
I have the following function:
let removeEven l =
let n = List.length l;
let list_ = [];
let seq_ = seq { for x in 1..n do if x % 2 <> 0 then yield List.nth l (x-1)}
for x in seq_ do
let list_ = list_ # [x];
list_;
It takes a list, and return a new list containing all the numbers, which is placed at an odd index in the original list, so removeEven [x1;x2;x3] = [x1;x3]
However, I get my already favourite error-message: Incomplete construct at or before this point in expression...
If I add a print to the end of the line, instead of list_:
...
print_any list_;
the problem is fixed. But I do not want to print the list, I want to return it!
What causes this? Why can't I return my list?
To answer your question first, the compiler complains because there is a problem inside the for loop. In F#, let serves to declare values (that are immutable and cannot be changed later in the program). It isn't a statement as in C# - let can be only used as part of another expression. For example:
let n = 10
n + n
Actually means that you want the n symbol to refer to the value 10 in the expression n + n. The problem with your code is that you're using let without any expression (probably because you want to use mutable variables):
for x in seq_ do
let list_ = list_ # [x] // This isn't assignment!
list_
The problematic line is an incomplete expression - using let in this way isn't allowed, because it doesn't contain any expression (the list_ value will not be accessed from any code). You can use mutable variable to correct your code:
let mutable list_ = [] // declared as 'mutable'
let seq_ = seq { for x in 1..n do if x % 2 <> 0 then yield List.nth l (x-1)}
for x in seq_ do
list_ <- list_ # [x] // assignment using '<-'
Now, this should work, but it isn't really functional, because you're using imperative mutation. Moreover, appending elements using # is really inefficient thing to do in functional languages. So, if you want to make your code functional, you'll probably need to use different approach. Both of the other answers show a great approach, although I prefer the example by Joel, because indexing into a list (in the solution by Chaos) also isn't very functional (there is no pointer arithmetic, so it will be also slower).
Probably the most classical functional solution would be to use the List.fold function, which aggregates all elements of the list into a single result, walking from the left to the right:
[1;2;3;4;5]
|> List.fold (fun (flag, res) el ->
if flag then (not flag, el::res) else (not flag, res)) (true, [])
|> snd |> List.rev
Here, the state used during the aggregation is a Boolean flag specifying whether to include the next element (during each step, we flip the flag by returning not flag). The second element is the list aggregated so far (we add element by el::res only when the flag is set. After fold returns, we use snd to get the second element of the tuple (the aggregated list) and reverse it using List.rev, because it was collected in the reversed order (this is more efficient than appending to the end using res#[el]).
Edit: If I understand your requirements correctly, here's a version of your function done functional rather than imperative style, that removes elements with odd indexes.
let removeEven list =
list
|> Seq.mapi (fun i x -> (i, x))
|> Seq.filter (fun (i, x) -> i % 2 = 0)
|> Seq.map snd
|> List.ofSeq
> removeEven ['a'; 'b'; 'c'; 'd'];;
val it : char list = ['a'; 'c']
I think this is what you are looking for.
let removeEven list =
let maxIndex = (List.length list) - 1;
seq { for i in 0..2..maxIndex -> list.[i] }
|> Seq.toList
Tests
val removeEven : 'a list -> 'a list
> removeEven [1;2;3;4;5;6];;
val it : int list = [1; 3; 5]
> removeEven [1;2;3;4;5];;
val it : int list = [1; 3; 5]
> removeEven [1;2;3;4];;
val it : int list = [1; 3]
> removeEven [1;2;3];;
val it : int list = [1; 3]
> removeEven [1;2];;
val it : int list = [1]
> removeEven [1];;
val it : int list = [1]
You can try a pattern-matching approach. I haven't used F# in a while and I can't test things right now, but it would be something like this:
let rec curse sofar ls =
match ls with
| even :: odd :: tl -> curse (even :: sofar) tl
| even :: [] -> curse (even :: sofar) []
| [] -> List.rev sofar
curse [] [ 1; 2; 3; 4; 5 ]
This recursively picks off the even elements. I think. I would probably use Joel Mueller's approach though. I don't remember if there is an index-based filter function, but that would probably be the ideal to use, or to make if it doesn't exist in the libraries.
But in general lists aren't really meant as index-type things. That's what arrays are for. If you consider what kind of algorithm would require a list having its even elements removed, maybe it's possible that in the steps prior to this requirement, the elements can be paired up in tuples, like this:
[ (1,2); (3,4) ]
That would make it trivial to get the even-"indexed" elements out:
thelist |> List.map fst // take first element from each tuple
There's a variety of options if the input list isn't guaranteed to have an even number of elements.
Yet another alternative, which (by my reckoning) is slightly slower than Joel's, but it's shorter :)
let removeEven list =
list
|> Seq.mapi (fun i x -> (i, x))
|> Seq.choose (fun (i,x) -> if i % 2 = 0 then Some(x) else None)
|> List.ofSeq

Resources