f#,max , Why does max (Operator) not return the longest list?

Why does max (Operator) not return the longest list?


Tag: f#,max

I want to find the longest of two lists. Consider the following code sample:

let xs = ['B']
let ys = ['A'; 'B']
let longest = max xs ys
printfn "%A" longest

Contrary to my expectation the output of this program is ['B'] rather than ['A'; 'B'].

Why does List<'T> implement max this way? How/where exactly is this implementation defined?

I can see that max requires comparison, which I believe implies the implementation of IComparable. List<'T> does that automatically by making use of the StructuralComparison attribute. But how does this automatic implementation look like?

What is the most concise alternative I can use to get the longest of two lists?


F# compares lists element by element. As 'B' > 'A' so it considers first list > second (lexicographic order) and breaks further comparison. You can use .Length property on list to compare lengths. Like this for example;

let longest = if xs.Length > ys.Length then xs else ys


val longest : char list = ['A'; 'B'] 


interpreting a script through F#

I really like F# but I feel like it's not succint and short enough. I want to go further. I do have an idea of how I'd like to improve it but I have no experience in making compilers so I thought I'd make it a scripting language. Then I...

Conditional Operator in F# (A?B:C) [duplicate]

This question already has an answer here: Does F# have the ternary ?: operator? 3 answers In C#, we have the conditional operator: [condition] ? [value if true] : [value if false] But I can't seem to find this in F#. Does it exist?...

Does let!/do! always run the async object in a new thread?

From the wikibook on F# there is a small section where it says: What does let! do?# let! runs an async<'a> object on its own thread, then it immediately releases the current thread back to the threadpool. When let! returns, execution of the workflow will continue on the new thread,...

How to get get max value in java? [closed]

I am writing a program that finds the taxes based on a person's income. So far the problem I am running into is some numbers that come out don't round up two decimal places and keep on going and I don't know how to get the max out of all...

Referencing event from .xaml file in .fs file

I want to declare an event in a XAML file and then add a handler in a fs file. The upper part of the XAML file would be something like (MouseRightButtonDown): <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="AboutStack" MouseRightButtonDown="AboutStack_MouseRightButtonDown" Title="About" SizeToContent="WidthAndHeight"> <StackPanel>... The F# file contains: open FsXaml type MainWindow = XAML<"MainWindow.xaml", true>...

How convert any record into a map/dictionary in F#?

I need to serialize arbitrary records into maps/dictionary. I imagine my end type look like this: type TabularData= array<Map<string, obj>> But I have problems in build a generic function that accept any record and turn them into Map....

F# computation expression transparent state passing with Bind

I have the following code that try to read a possibly incomplete data (image data, for example) from a network stream using usual MaybeBuilder: let image = maybe { let pos = 2 //Initial position skips 2 bytes of packet ID let! width, pos = readStreamAsInt 2 pos let! height,...

How to rewrite this C# code

I have this C# code: const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = stream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } I need to rewrite it in F#. I can do it like this: let bufferLen : int =...

Why embed async in async?

I read the following code from the book Expert f#, Why the function collectLinks embeds let! html = async { .... } in the outer async block? How about just flat it by removing the inner async? Same question for the function waitForUrl in urlCollector which has a do! Async.StartChild...

a maximum value per rowname(1, 2, or A, B..) per multiple columns in R

I want to a maximum value per rowname(1, 2, or A, B..) per multiple columns(samples). I have a matrix. id sample1 sample2 sample3 ... 1 16498 2416 12555.5 1 21282.5 3342 22202 2 18558 2308 na 2 17966 3047 na 2 398 176.5 na 3 347 227 201.5 3 604.5...

Why is FSharp.Data.SqlClient record exposed as object?

I'm working on a demo where I can show how easy it is to use the SqlClient type provider in a F# library and then consume it from C#, I think this might be one way to get things into projects. Since many people using C# want to use interfaces...

Duck typing with type provider instances [duplicate]

This question already has an answer here: How do I write this member constraint in F#? 1 answer I am writing an F# script to operating on tables in a database. All of the tables have a Guid Id property. I want to make use of duck typing to...

How to handle Arithmetic operation OverflowException in F#?

I'm doing Project Euler problem 1 in F#: Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples...

Filtering a sequence of options and collecting the values of all the Somes. Is there a built-in function in F# for that?

A common pattern in F# is to want to filter something by whether it is "Some"thing and in case it is, getting its value: module Option = let values s = s |> Seq.filter Option.isSome |> Seq.map Option.get I have the idea I've seen something like that in the F#...

How do I store the value of the max integer in an array before repeating loop?

It's been a couple hours. I don't understand arrays well enough to determine the right way to save a value as max and then determine the maximum value within the array. Please help explain how to make the for loop correctly. Thanks. #include <stdio.h> #include <conio.h> #define SIZE 3 int...

How can I resolve the “Could not fix timestamps in …” “…Error: The requested feature is not implemented.”

I have been trying to build a project in F# on Linux that I have located here on github. It's a basic kata project that I am working on as a demo. However on Linux (specifically Ubuntu 14.04 LTS Desktop) I haven't been able to get it to build yet...

d3.max didn't get the correct value [duplicate]

This question already has an answer here: D3.js scale returning wrong values from dataset 1 answer I am using d3.js to render some data and the data set is a csv file called bar-data.csv like this: date,value,duration www.sina.com,53,100 www.baidu.com,165,2000 www.qq.com,269,690 www.youku.com,421,224 www.facebook.com,405,345 www.apple.com,376,777 www.cnn.com,359,298 www.cctv.com,433,333 www.google.com,455,500 www.boston.com,670,274 However when...


I'm working on Oracle SQL and HR database, I'm trying to select maximum salary in department like this: SELECT MAX(salary), department_id FROM employees GROUP BY department_id; It works fine, but I want to know >who< is earning the most, so I simply change query this way: SELECT first_name, last_name, MAX(salary),...

How to find a max value

I am new to python, and am trying to learn it with newmans computational physics. I was trying to make a program to solve one of the exercises. It is to calculate the highest binding energy using an approximate formula . I made this program, to find the binding energy:...

MySQL Group By - Get row associated with max() amount

What I am trying to get is the row contents containing the highest price. I am not sure if I need to self-join, or use a having statement. Most of the attempts I have tried netted me no returned rows. Effectively I want to say "WHERE PRICE IS MAX". I...

What is the difference between member val and member this in F#?

When I created a class containing a generic, mutable .NET Stack in F# like the example below, that stack ignores anything I push onto it. open System.Collections.Generic type Interp(code: int array) = member val PC = 0 with get, set member this.stack: Stack<int> = new Stack<int>() member this.Code = code...

F# - Recursive function to copy a list

I wrote this code to recursively copy my list: let sp = [2;4;6;8;10] let copy (s1:'a list) = let rec copy acc ind = if(ind>=0) then copy (s1.[ind]::acc) (ind-1) else acc copy [] (s1.Length-1) sp |> copy |> printfn "%A" How to make this code easier?...

F# Discriminated Union - “downcasting” to subtype

I don't really know what the proper title for this question should be, but: I have a discriminated union called MyDiscriminatedUnion in F#: type MyDiscriminatedUnion = | Foo of Foo | Bar of Bar where Foo and Bar are record types: type Foo = { ... } type Bar =...

Asynchronously manipulating data from streamReader in F#

On the line of Read large txt file multithreaded?, I have the doubt of whether it is equivalent to pass to each thread an sliced chunk of a Seq and whether it will safely handle the paralellism; is it StreamReader thread-safe? Here is the code I am using to test...

Excel with AND, IF, MAX

I can't quit figure out what I am doing wrong here, I know how to do the formula in multiple steps but can not figure out how to do it in one step all together. So what I am trying to do here is in column A there is numbers...

F# I want to filter my output

I have a problem which I have simplified for the purpose of this question. Let's just say I have 2 lists. The first actually represents a list of classes but for this purpose, let's say it simply represents a list of ints (2,4,6,8,10). I have another list of ints that...

how to get more than one max records in MySQL

This is the answers that I want to get.But if I used MAX() function in MySQL, it just return one record.How to handle it? A_plus ID 2 12345 2 45678 As decribed above,The SQL I used as fellow,but it just return one record. SELECT MAX(A_plus_Num) AS A_plus, ID FROM (SELECT...

How to recursively identify cells of specific type in grid?

I'm learning F# and I'm building a minesweeper app. As part of that, I'm trying to have a method that detonates all adjacent mines if a mine is detonated, recursively. So if I have a grid like: | 0 | 1 | 2 | ------------------------ 0 | E-1 | M...

How to implement generics with type annotations in F#

I have the following skeleton of code: type MyException<'T> () = inherit Exception() type IMyInterface = abstract member Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> : string -> int type MyClass = interface IMyInterface with member this.Method s = let i = s.IndexOf "a" if...

FParsec parses only first half

In my AST, I have something like this: type Program = Declaration list and Declaration = | TypedefDeclaration of TypedefDeclaration and TypedefDeclaration = | Typedef1 of Name * TypeName | Typedef2 of Name * Name For parsing both of the statements, I have used something like this: let tdefpartial =...

Return a modified version of same type in F#

If I've got a class hierarchy like type Employee(name) = member val name: string = name type HourlyEmployee(name, rate) = inherit Employee(name) member val rate: int = rate type SalariedEmployee(name, salary) = inherit Employee(salary) member val salary: int = salary And I want a function that updates the name field...

F# - Result is list of list of int instead of a list of int

I have quite a complex problem that I have simplified for the purpose of this question. Let's just say the problem is as follow: I want a list of the first 3 numbers (1,2,3) added to all of these numbers: 0,10,20 So I want the following desired output: all =...

Doc.Checkbox 'change' event does not occur in Websharper.UI.Next

I have reactive Var variable varDone and Doc.Checkbox for its representation named cbDoc. After changing the value of varDone I need to call my function. For this, I wrote the code illustrated in the following pseudo-code: open WebSharper open WebSharper.UI.Next open WebSharper.UI.Next.Html open WebSharper.UI.Next.Notation // declaring reactive bool variable let...

psql max group by just for some columns

I have a problem in a psql query. I don't know how to select only the maximum value from a subset of two columns. It's very hard to explain the problem without an example, so I write one: I have a table like that: Athlete | Category | Points at1...

How to get maximum value from a column in a data.frame and get ALL records

I have a data.frame and I wish to get the row that contains the maximum value for the given column Total Txn_date Cust_no Acct_no cust_type Credit Debit Total 09DEC2013 17382 601298644 I 1500 0 1500 16DEC2013 17382 601298644 I 500 0 500 17DEC2013 17382 601298644 I 0 60 60 18DEC2013...

exception is not coming with sql max function

I wrote the below query expecting NO_DATA_FOUND exception to be thrown when no rows found. BEGIN SELECT MAX(A_id) + 1 INTO id_variable from table_A; EXCEPTION WHEN NO_DATA_FOUND THEN SELECT MAX(A_id) + 1 INTO id_variable from table_A_archive; END; there is no data in table_A but no exception was thrown and eventually...

F# - writing an (GA) evaluation function in F#

Background: I am currently working on a genetic algorithm (GA) in F#. (I come from a strong C# background and have only been using F# for a day now) Problem: I have an error evaluation function to determine how valid a proposed solution is.Lets assume a simplified error algorithm: Calculate...

Can you list the contents of a namespace or module in F#

Similar to this question about clojure, is it possible to list the contents of a namespace or module in F#? When I open a namespace for a loaded DLL I'm not receiving an error that the namespace doesn't exist, but then when I try to use the documented functions I'm...

Post messages from async threads to main thread in F#

There is a subscription to an observable that sends out log messages. Some of the log messages come from other threads because they are are in F# async blocks. I need to be able to write out the messages from the main thread. Here is the code that currently filters...

Duplicate Key in index of Deedle Series

I have a list of events that occur in a system. My goal is to take the list of events and create a sliding window of the series to determine rate event occurrences. The events are loaded into the events list from an application outside of this scope of the...

When are let bindings in code quotations replaced with their values?

If I run the first example from MSDN (https://msdn.microsoft.com/en-us/library/dd233212.aspx) in the F# Interactive window, I get the expected output: fun (x:System.Int32) -> x + 1 a + 1 let f = fun (x:System.Int32) -> x + 10 in f 10 But if I run it in the Main from my...

Select max value from different column in a row in oracle database

My table in oracle database is like this: Rollno | mark1 | Mark2 | mark3 --------+-----------+-----------+--------+ 101 | 10 | 20 | 30 102 | 22 | 44 | 08 103 | 55 | 11 | 14 --------+-----------+-----------+--------+ And I want output like Rollno | MAX(Mark1,mark2,mark3) --------+-------------------------+ 101 | 30...

A function to calculate cumulative maximum for a double matrix in MATLAB

Is there any function that can calculate cumulative maximum for a double matrix? I have a 1*3000 matrix and I need to calculate the cumulative maximum. For example if the matrix is: A = [8 3 6 7 9 10 6 2 2 3] The cumulative maximum array will be:...

F# Custom operators

I've defined a custom operator in F# like this: static member (&?) value defaultValue = if value = null then defaultValue else value The operator is defined within a type and should be called in the following scenario: I'm retrieving information about the system processors using WMI. Now i want...

Properly implement F# Unit in C#

This question is not about C#/F# compatibility as in this one. I'd like to know the proper way to implement a type like F# Unit in place of using void. Obviously I'll discard this result and I'll not expose this type to the outside world. Wondering if an empty class...

shift/reduce and reduce/reduce errors in F# using fsyacc and fslex

I'm creating my own external DSL, which I intend to be pretty small and include some basic functionality. When I compile my project, it builds successfully but it shows a lot of shift/reduce and reduce/reduce errors. And most of them are around my binary operators. Here is part of my...

Is this definition of a tail recursive fibonacci function tail-recursive?

I've seen around the following F# definition of a continuation-passing-style fibonacci function, that I always assumed to be tail recursive: let fib k = let rec fib' k cont = match k with | 0 | 1 -> cont 1 | k -> fib' (k-1) (fun a -> fib' (k-2)...

Select where max date

I want to select the last note from notes with the following query: SELECT cn.Note, MAX(cn.Date) FROM CarsNote cn WHERE CustomerID = '80' AND cn.Type = 'INFO' GROUP BY Note When I execute this query i get four results but i want only the last note. When i do SELECT...

All the F# templates in VS 2015 RC disappear

I installed in a fresh Win 8.1 machine VS 2015 RC. I load VS and create a F# project. Fine. Eventually, I do some other stuff (that I have not remember) and then I found that no single F# template (for projects) exist anymore in VS. Only C#/VB ones....

F# “The value of constructor … not defined”

So, this is my second F# console application. The code goes like this: let rec fact n = if n = 1 then 1.0 else float(n)*fact(n-1);; let rec pow x n = if n = 1 then x else float(x) * pow x (n-1);; let rec func1 eps x n...