As an example, the two expressions evaluated below have the same "printed" representation, namely ((A) (A)), but they have very different internal structure. Here the structure is shared:
* (let ((item '(a))) (list item item))
((A) (A))
Here each (a) is a distinct entity:
* '((a) (a))
((A) (A))
Specifically, the value of the first expression is a two-element list were the two elements are identical; the value of the second expression is also a two-element list, but its two elements are distinct (i.e. not identical).
How can I represent these two values in a way that makes this difference in their internal structures more apparent?
What you are looking for is *print-circle*:
* (setq *print-circle* t)
T
* '((a) (a))
((A) (A))
* (let ((item '(a))) (list item item))
(#1=(A) #1#)
If you want "print -
read consistency", you should investigate
*print-readably* and
with-standard-io-syntax:
(equal (read-from-string (with-standard-io-syntax (write-to-string x)))
x)
should either return T or signal an error of type
print-not-readable.
Related
Let's say our Variable Five is a tuple of five elements.
How do we write an expression that evaluates to (and prints) the first element, but only if all five elements are identical?
For example, given this following tuple:
Five = {4, 4, 4, 4, 4}.
I'm trying to use element(_,_). Statement as:
element(1, Five) =:= element(2, Five).
But this only give me the evaluation of the first element VS the 2nd one, not all together.
Any idea how I can evaluate the first one with all the other elements the same time?
{ .................. } = Five, ....................
If you know the size of the tuple (e.g. 5 as in your example), you could pattern match using the same variable:
case Five of
{X, X, X, X, X} -> io:format("~w", [X]), X;
_Otherwise -> ok
end
Of course, the same can be done in function clauses.
If the size of the tuple is unknown, one way would be to convert it to a list using tuple_to_list/1 and, for example, use lists:all/2:
[H | T] = tuple_to_list(Five),
IsSame = lists:all(fun (E) -> E =:= H end, T),
case IsSame of
true -> io:format("~w", [H]), H;
false -> ok
end
So I want a function that receives an array of Tuple<int,int> and returns the same type but with different values.
What I want to do is a function that returns this kind of values:
f( [1,10; 2,20; 3,40; 4,70] ) = [2,10; 3,20; 4,30]
So as you can see, the first number is basically unchanged (except the 1st item is not picked), but the last number is the substraction of the current number with the previous number (20 - 10 = 10, 40 - 20 = 20, ...).
I've tried to come up with an algorithm in F# that doesn't involve mutability (using an accumulator for the previous value would mean I need a mutable variable), but I can't figure out. Is this possible?
Using built-in functions. In this case, you can use Seq.pairwise. The function takes a sequence of inputs and produces a sequence of pairs containing the previous value and the current value. Once you have the pairs, you can use Seq.map to transform the pairs into the results - in your case, take the ID of the current value and subtract the previous value from the current value:
input
|> Seq.pairwise
|> Seq.map (fun ((pid, pval), (nid, nval)) -> nid, nval-pval)
Note that the result is a sequence (IEnumerable<T>) rather than a list - simply because the Seq module contains a few more (useful) functions. You could convert it back to list using List.ofSeq.
Using explicit recursion. If your task did not fit one of the common patterns that are covered by some of the built-in functions, then the answer would be to use recursion (which, in general, replaces mutation in the functional style).
For completeness, the recursive version would look like this (this is not perfect, because it is not tail-recursive so it might cause stack overflow, but it demonstrates the idea):
let rec f list =
match list with
| (pid, pval)::(((nid, nval)::_) as tail) ->
(nid, nval-pval)::(f tail)
| _ -> []
This takes a list and looks at the first two elements of the list (pid, pval) and (nid, nval). Then it calculates the new value based on the two elements in (nid, nval-pval) and then it recursively processes the rest of the list (tail), skipping over the first element. If the list has one or fewer elements (the second case), then nothing is returned.
The tail-recursive version could be written using the "accumulator" trick. Instead of writing newValue::(recursiveCall ...) we accumulate the newly produced values in a list kept as an argument and then reverse it:
let rec f list acc =
match list with
| (pid, pval)::(((nid, nval)::_) as tail) ->
f tail ((nid, nval-pval)::acc)
| _ -> List.rev acc
Now you just need to call the function using f input [] to initialize the accumulator.
> let values = [(1, 10); (2, 20); (3, 40); (4, 70)];;
val values : (int * int) list = [(1, 10); (2, 20); (3, 40); (4, 70)]
> values
|> Seq.pairwise
|> Seq.map (fun ((x1, y1), (x2, y2)) -> (x2, y2 - y1))
|> Seq.toList;;
val it : (int * int) list = [(2, 10); (3, 20); (4, 30)]
Seq.pairwise gives you each element in a sequence as a pair, except the first element, which is only available as the predecessor of the second element.
For example:
> values |> Seq.pairwise |> Seq.toList;;
val it : ((int * int) * (int * int)) list =
[((1, 10), (2, 20)); ((2, 20), (3, 40)); ((3, 40), (4, 70))]
Second, Seq.map maps each of these pairs of pairs by using the desired algorithm.
Notice that this uses lazy evaluation - I only used Seq.ToList at the end to make the output more readable.
BTW, you can alternatively write the map function like this:
Seq.map (fun ((_, y1), (x2, y2)) -> (x2, y2 - y1))
Notice that instead of x1 is replaced with _ because the value isn't used.
Mark and Tomas have given really good solutions for the specific problem. Your question had a statement I think warrants a third answer, though:
(using an accumulator for the previous value would mean I need a mutable variable)
But this is actually not true! List.fold exists exactly to help you process lists with accumulators in a functional way. Here is how it looks:
let f xs = List.fold (fun (y, ys) (d, x) -> x, (d, x-y) :: ys)
(snd (List.head xs), [])
(List.tail xs)
|> snd |> List.rev
The accumulator here is the argument (y, ys) to the fun ... in the first line. We can see how the accumulator updates to the right of the ->: we accumulate both the previous element of the list x, as well as the new list we're constructing (d, x-y)::xs. We'll get that list in reverse order, so we reverse it in the end with List.rev.
Incidentally, List.fold is tail-recursive.
Of course, Tomas and Mark's solutions using Seq.pairwise are much neater for your particular problem, and you'd definitely want to use one of those in practice.
Whenever we need to create a sequence from another sequence, where one element in the output is a function of its predecessors, scan (docs) comes in handy:
[1,10; 2,20; 3,40; 4,70]
|> List.scan (fun ((accA, accB), prevB) (elA, elB) -> ((elA, elB-prevB), elB)) ((0, 0), 0)
|> Seq.skip 2
|> Seq.map fst
yields:
[(2, 10); (3, 20); (4, 30)]
I have a list of ((a)(b)(f(x))). What i would like to get is a linked list structure of((a)(b)(f(x1))(a)(b)(f(x2))(a)(b)(f(x3)))). That is, repeatively appending the list the on the basis of requirement of the user and the value of the variable is chaning so that its value will be unique from each other. How can i implement it in LISP?
? (let ((list '((a) (b) (f (x))))
(n 3))
(flet ((copier (l n)
(setf l (copy-tree l))
(let ((sym (first (second (third l)))))
(setf (first (second (third l)))
(intern (format nil "~a~a"
(symbol-name sym)
n))))
l))
(loop for i from 1 upto n
nconc (copier list i))))
((A) (B) (F (X1)) (A) (B) (F (X2)) (A) (B) (F (X3)))
Total F# n00b question.
How do I sort a LIST data structure?
Edit: Sorry, my data structure is actually a LIST.
maybe i should add my code since just using ".sort" hasn't worked:
let getDataFromDb (db: MyDB) Id =
Query.query <# seq {
big honking database/FLinq query
yield (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
} #> |> List.ofSeq
when I change the last line of code to this:
} #> |> List.ofSeq.sortBy fst
I get the following:
Error 1 The field, constructor or member 'sortBy' is not defined
ugh, what a pain. I'm trying this now:
|> List.ofSeq |> List.sortBy
But I'm getting this:
Error 1 Type mismatch. Expecting a (Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list -> 'a but given a ('b -> 'c) -> 'b list -> 'b list The type '(Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list' does not match the type ''a -> 'b'
Seq.sortBy would do that.
However sorting implies you know the key values of the full sequence at the time of sorting, so by definition you cannot use this on infinite sequences.
Edit:
The equivalent for lists has the same name:
List.sortBy
MSDN example:
let sortedList2 = List.sortBy (fun elem -> abs elem) [1; 4; 8; -2; 5]
printfn "%A" sortedList2
Edit 2:
From your new example it seems like you have a list of tuples. Now it depends on what item in the tuple you want to search by.
As others said, Seq.sortBy is the way to go. If you're using FLinq to read some data from a database, then it is a good idea to include the sorting as part of the database query (enclosed in <# .. #>) so that the sorting is done on the SQL server:
let getDataFromDb (db: MyDB) Id =
<# seq { big honking database/FLinq query
yield (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
|> Seq.sortBy (fun (_, _, _, _, _, i, _, _, _) -> i) #>
|> List.ofSeq
To make this a little nicer, you could return tuple containing key and all other elements as nested tuple e.g key, (sec, pm, ..., lt) and then just sort using the first element:
|> Seq.sortBy (fun (k, _) -> k)
(I had some troubles using tuples with LINQ to Entities, but I believe that it should work in LINQ to SQL).
Use:
Query.query <# ... #>
|> List.sortBy (fun (sec, _, _, _, _, _, _, _, _) -> sec)
Note that using tuples with that many elements is really bad style in F#. Use something more structured like a record type to give names to the fields and avoid confusion.
I've just started messing around with F# and am trying to do some basic parallel computation to get familiar with the language. I'm having trouble with type mismatches. Here's an example:
let allVariances list =
seq {
for combination in allCombinations list do
yield (combination, abs(targetSum - List.sum combination))
}
let compareVariance tup1 tup2 =
if snd tup1 < snd tup2 then
tup1
else
tup2
let aCompareVariance tup1 tup2 =
async { return compareVariance tup1 tup2 }
let matchSum elements targetSum =
allVariances elements
|> Seq.reduce aCompareVariance
|> Async.Parallel
|> Async.RunSynchronously
So, "allVariances elements" produces a seq<float list * float>. CompareVariance takes two of those <float list * float> tuples and returns the one with the smaller second item (variance). My goal is to use Reduce to end up with the tuple with the smallest variance. However, I get a type mismatch on the aCompareVariance argument:
Error 1 Type mismatch. Expecting a float list * float -> float list * float -> float list * float but given a float list * float -> float list * float -> Async<float list * float> The type 'float list * float' does not match the type 'Async<float list * float>'
It seems like the Async return type isn't accepted by Reduce?
Seq.reduce takes a function and a sequence and reduces the list using the function. That is, the outcome of reducing a sequence {a1;a2;a3;...;an} with function f will be f(f(...f(f(a1,a2),a3),...),an))...). However, the function you're passing can't be applied this way, because the return type (Async<float list * float>) doesn't match the argument types (float list * float). What exactly are you trying to achieve?
Also, keep in mind that async computations are great for asynchronous work, but not ideal for parallel work. See F#: Asynch and Tasks and PLINQ, oh my! and Task Parallel Library vs Async Workflows.
EDIT
Here's one way to write a function which will reduce items more like you expected, operating sort of like this:
[|a1; a2; a3; a4|]
[|f a1 a2; f a3 a4|]
f (f a1 a2) (f a3 a4)
At each stage, all applications of f will take place in parallel. This uses Async.Parallel, which as mentioned above is probably less appropriate than using the Task Parallel Library (and may even be slower than just doing a normal synchronous Array.reduce). As such, just consider this to be demonstration code showing how to piece together the async functions.
let rec reduce f (arr:_[]) =
match arr.Length with
| 0 -> failwith "Can't reduce an empty array"
| 1 -> arr.[0]
| n ->
// Create an array with n/2 tasks, each of which combines neighboring entries using f
Array.init ((n+1)/2)
(fun i ->
async {
// if n is odd, leave last item alone
if n = 2*i + 1 then
return arr.[2*i]
else
return f arr.[2*i] arr.[2*i+1]})
|> Async.Parallel |> Async.RunSynchronously
|> reduce f
Note that converting items to and from Async values all happens internally to this function, so it has the same type as Array.reduce and would be used with your normal compareVariance function rather than with aCompareVariance.