Menu
  • HOME
  • TAGS

Multi-case parameterized active patterns returning error FS0722 Only active patterns returning exactly one result may accept arguments

Tag: compiler-errors,f#,active-pattern

Since I only found Japanese pages about this error, I figured, let's log it and ask here, since my Japanese is kinda rusty.

If I have the following FSharp active pattern (simplified example):

let (|InRange|OutOfRange|) from too =
    function
    | input when input >= from && input <= too -> InRange
    | _ -> OutOfRange

It compiles perfectly and shows its type as:

val ( |InRange|OutOfRange| ) :
  from:'a -> too:'a -> _arg1:'a -> Choice<unit,unit> when 'a : comparison

But when I try to use it, i.e. as follows, it throws an error:

let test i = match i with
             | InRange 10 20 -> "in range"
             | _ -> "out of range"

Throws: error FS0722: Only active patterns returning exactly one result may accept arguments

I can resolve it by turning it into two single-case parameterized active patterns, each returning None/Some(x), but I'm still wondering why I am not allowed doing so and/or whether there's syntax I can use that I am not aware of. I am also wondering why it compiles, but I cannot use it?

Best How To :

The simplest solution would be refactoring this into a partial active pattern:

let (|InRangeInclusive|_|) lo hi x =
    if lo <= x && x <= hi then Some () else None

Then you may even combine them in something like this:

let test i = match i with
         | InRangeInclusive 10 20 -> "in first range"
         | InRangeInclusive 42 100 -> "in second range"
         | _ -> "out of range"

Note, I took my liberty to give the pattern a better name, because those who would use your code may be confused about its behavior with corner cases.

I'm still wondering why I am not allowed doing so?

Why can't non-partial active patterns be parameterized in F#?

Duck typing with type provider instances [duplicate]

f#,type-providers,duck-typing

I'll maintain that this is a duplicate, but here's the exact code you need to get going: let inline getAllIds< ^a when ^a : not struct> (table : Table< ^a>) = table |> Seq.map (fun x -> (^a : (member Id : Guid with get) x)) Alternatively, the following syntax...

App crashing after pushing button, but the action is working

android,button,android-studio,compiler-errors

It crashed if you dont press btn1 because without press it, mpAudio will be null. Then when onPause call, mpAudio.release(); will cause NullPointerException. Note that: onPause is called whenever the activity is not shown on screen but is still running(in your case, you start other activity with btn2,3 then it...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)

c++,osx,c++11,compiler-errors,llvm

This line of code is very ambiguous: for (auto it : _unhandledFiles)//ERROR HERE auto uses template argument deduction, so std::string s; std::string& sr = sr; auto x = sr; in the above code x is deduced to be of type std::string, not std::string&. So your loop is equivalent to: for...

Access to reference in member variable discards constness

c++,c++11,reference,compiler-errors,const

Yes, this is correct behaviour. The type of ref is Foo &. Adding const to a reference type1 does nothing—a reference is already immutable, anyway. It's like having a member int *p. In a const member function, its type is treated as int * const p, not as int const...

output with lseek and open functions, keep getting compile or running time error

c,compiler-errors,fwrite,truncate,lseek

You have mistyped the flags for open: O_RDWR|0_TRUNC|0_CREAT Should be spelled with the letter O instead of the digit 0: O_RDWR | O_TRUNC | O_CREAT There is (at least) another mistake here: write(1, (const void *)&buf1, 15); You are writing the value of the pointer buf1 to stdout plus a...

Error when overwriting value in unsigned char array [closed]

c++,arrays,compiler-errors

Don't you use your_array[index] = "C"; instead of your_array[index] = 'C'; ? Anyway you should put some code on your post to show us where is the error....

MultipartEntityBuilder.create cannot be resolved to a type

java,eclipse,compiler-errors

If you want to call a method, the expression on the right hand side of the assignment shouldn't start with new: MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); Otherwise the compiler expects a constructor call, which would mean you'd call the default constructor of the create class that is a static inner class...

F# “The value of constructor … not defined”

visual-studio-2010,f#

When you use F# interactive, you first need to evaluate the code that defines the functions that you want to use. So, if you select just the last line of your script, you get an error. I suppose you are using Alt+Enter to send the code to F# interactive -...

F# computation expression transparent state passing with Bind

f#,computation-expression

@bytebuster is making good points of maintainability about custom computation expressions but I still thought I demonstrate how to combine the State and Maybe monad into one. In "traditional" languages we have good support for composing values such as integers but we run into problems when developing parsers (Producing values...

Dereferencing pointer to incomplete type error for struct member access in Python swig C wrapper

python,c,gcc,compiler-errors,swig

You declare this type: struct WFDB_siginfo and use this one: struct WFDB_Siginfo which is different (note the uppercase S), so gcc truly believes struct WFDB_Siginfo is another type which has not been declared yet....

Unhandled Exception when calling SipProfile.Builder from Android SIP Class

java,android,object,android-studio,compiler-errors

The problem is, SipProfile.Builder may fail at runtime. It depends on server not the code. Then we should always use it with try-catch block. This is the working code: try { String id = txtId.getText().toString(); String username = txtUsername.getText().toString(); SipProfile.Builder builder1 = new SipProfile.Builder(id, username); } catch(java.text.ParseException e){ e.printStackTrace(); }...

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

f#

As far as I know, there's no such function that does exactly that (I had a glance at the FSharpReflectionExtensions module), but you can write one yourself. All the building blocks are there. As strange as it may seem, namespaces aren't part of the .NET platform that both F#, C#,...

Unable to Access Anonymous Class Method in Java

java,compiler-errors,anonymous-class,anonymous-inner-class

You can only call existing method from the Reference of Test class. So if you have declared doStuff() method then only you can call it with Test testObj reference. See this SO question Is it possible to call subclasses' methods on a superclass object? But you can surely call new...

F# - Recursive function to copy a list

list,f#

Performing a lookup into the list (as well as getting the length of the list) is not very efficient, because the library needs to iterate over the entire list (or over the first N elements). For this reason, doing this is not really idiomatic in F#. You can still keep...

F# Discriminated Union - “downcasting” to subtype

f#,discriminated-union

This is a common mistake when coming from an OO language: there are no subtypes involved in this code. The fact that you named your union cases the same as the type of the field they contain can make this confusing though, so let me give a slightly different example:...

F# I want to filter my output

f#

This one seems to be reasonable easy: let filterWith set2 set1 = List.zip set1 set2 |> List.filter (fun (_,x) -> x=1) |> List.map fst usage: let set1 = [2;4;6;8;10] let set2 = [1;0;0;1;1] set1 |> filterWith set1 if you would choose to use a list of bools for your set2...

Float comparision in C [duplicate]

c,if-statement,compiler-errors,floating-point,floating-point-precision

Because 0.5 has an exact representation in IEEE-754 binary formats (like binary32 and binary64). 0.5 is a negative power of two. 0.6 on the other hand is not a power of two and it cannot be represented exactly in float or double.

Return a modified version of same type in F#

f#

If you're looking for something both pure and idiomatic F#, then you shouldn't be using an inheritance hierarchy in the first place. That's an object-oriented concept. In F#, you could model Employee like this, using algebraic data types: type HourlyData = { Name : string; Rate : int } type...

what is the compile error in this code [closed]

c,linux,compiler-errors,fwrite,pid

In the following two lines: write(p[1], "abcdefghi', sizeof("abcdefghi")); write(p[1], "123456789', sizeof("123456789")); Replace "abcdefghi' with "abcdefghi" and "123456789' with "123456789"...

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

web,f#,websharper

What happens is that Doc.AsPagelet adds a wrapper around the doc, so you are adding an event listener to that wrapper. And even if it did not, you would be adding an event listener to the Div0 you created instead of the CheckBox itself. That being said, there are two...

syntax error : missing ')' before 'constant'

c,compiler-errors,macros,syntax-error,c-preprocessor

#define is a preprocessor MACRO which acts as a textual replacement in the preprocesssing stage. In your case, with a MACRO like #define N 10 and then with a function like void displayMatrix(int *arr,int M, int N); it turns out to be void displayMatrix(int *arr,int M, int 10); //note the...

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

.net,f#

The easiest way is to use Seq.choose s |> Seq.choose id Here we use id as the input is the same as the output...

Multiple definition and file management

c,arrays,compilation,compiler-errors,include

include is a preprocessor directive that includes the contents of the file named at compile time. The code that conditionally includes stuff is executed at run time...not compile time. So both files are being compiled in. ( You're also including each file twice, once in the main function and once...

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

linux,build,f#

This is usually a sign that you should update your mono. Older mono versions have issues with their unzip implementation

How to implement generics with type annotations in F#

generics,f#

I think you have to parametrise MyClass: type MyClass<'T> = interface IMyInterface with member this.Method s = let i = s.IndexOf "a" if i = -1 then raise (new MyException<'T> ()) i or repeat constraints on your method: type MyClass = interface IMyInterface with member this.Method<'T when 'T : (new:...

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

f#

you can pattern match on the list to count this up like this: let rec mismatchs xs = match xs with | [] | [_] -> 0 | (a::b::t) -> (if a > b then 1 else 0) + mismatchs (b::t) a slight problem with that is, that the function...

How to recursively identify cells of specific type in grid?

recursion,f#,tail-recursion

This will return a set of all detonated cells including the one that started the chain reaction. module Location = type T = {Row: int; Column: int } let subtract l1 l2 = {Row=l1.Row - l2.Row;Column=l1.Column-l2.Colum let detonate (field:Field.T) (start:Cell.T) = let rec inner cells m acc = match cells...

FParsec parses only first half

parsing,f#,dsl,fparsec

You're right, the line: let ptypedef = ptypedef1 <|> ptypedef2 is the problem. ptypedef1 is consuming some of the input so attempt needs to be used to backtrack when it fails so that ptypedef2 parses the text you're expecting it to, the fixed line would look like: let ptypedef =...

Fortran compiler for mac to read program

compiler-errors,fortran,fortran77,g77

The ACCEPT statement is not part of Fotran standard. It is a non-standard extension and therefore your program is not a FORTRAN 77 program and you cannot expect all compilers to compile it. Notably, g77 does not support this extension https://gcc.gnu.org/onlinedocs/g77/TYPE-and-ACCEPT-I_002fO-Statements.html The modern successor of g77 - gfortran - does...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

Asynchronously manipulating data from streamReader in F#

asynchronous,f#,streamreader

Your Data value has a type seq<string>, which means that it is lazy. This means that when you perform some computation that accesses it, the lazy sequence will create a new instance of StreamReader and read the data independently of other computations. You can easily see this when you add...

interpreting a script through F#

scripting,f#,interpreted-language

I really like F# but I feel like it's not succinct 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. F#...

All the F# templates in VS 2015 RC disappear

templates,f#,visual-studio-2015

That's a bug in 2015 RC. It's already fixed, but we need to wait for another release. https://github.com/Microsoft/visualfsharp/issues/411

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

f#

Which part of that statement do you find surprising? That parts of a single async can execute on different threadpool threads, or that a threadpool thread is necessarily being released and obtained on each bind? If it's the latter, then I agree - it sounds wrong. Looking at the code,...

Referencing event from .xaml file in .fs file

wpf,xaml,f#,fsxaml

As there's no code-behind you can't call the method from XAML but need to attach it from the outside: let AboutStack_MouseRightButtonDown args = // do whatever you want, return unit wnd.MouseRightButtonDown.Add(AboutStack_MouseRightButtonDown) or e.g. wnd.MouseRightButtonDown.Add(fun _ -> MessageBox.Show("Click!") |> ignore) Another approach would be to use a model (DataContext) and bindings...

Duplicate Key in index of Deedle Series

f#,deedle

One of the design decisions we made in Deedle is that a series can be treated as a continuous series (rather than a sequence of events) and so Deedle does not allow duplicate keys (which make sense for events but not for time series). I wish there was a nicer...

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

parsing,f#,dsl,lexer,fsyacc

First, your Expression non-terminal has two identical productions: Expression: | IDENTIFIER ASSIGN Expression { ScalarAssignmentExpression($1, $3) } | IDENTIFIER ASSIGN Expression { ArrayAssignmentExpression($1, $3) } So there is absolutely no way for the parser to distinguish between them, and thus know which action to take. I suppose you can tell...

F# Custom operators

f#,operator-overloading

Your operator takes an arg of type obj so you should define it as a standalone function, not a type member. let (&?) (value:obj) (defaultValue:'a) = match value with | null -> defaultValue | _ -> unbox value Now you can do this: let voltage = m.["VoltageCaps"] &? 0 I...

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

.net,f#,immutability

If you try to compile the first version, and then use e.g. Reflector to decompile it to C#, you'll see that the stack member is defined like this: public class Interp { public Stack<int> stack { get { return new Stack<int>(); } } // Other members omitted for clarity... }...

Properly implement F# Unit in C#

c#,f#,functional-programming

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way). However, you can actually find the implementation of F# unit in the core library:...

Haskell: `==' is not a (visible) method of class

haskell,compiler-errors,instance,equality,typeclass

It isn't clear what you are trying to achieve. Here are some thoughts: When you declare an instance of a class like instance (Eq a) => PartOrd a, you are expected to provide implementations for the functions in PartOrd a (ie partcmp, not == and \=). The compiler is telling...

Why embed async in async?

f#

I can think of one reason why async code would call another async block, which is that it lets you dispose of resources earlier - when the nested block completes. To demonstrate this, here is a little helper that prints a message when Dispose is called: let printOnDispose text =...

Can't reference a variable from App.config

c#,compiler-errors,app-config

Use the system.configuration class. string str = System.Configuration.ConfigurationManager .AppSettings["someAppSetting"] .ToString(); ...

How to throw an error in the LESS compiler

css,compiler-errors,less,throw,less-mixins

Suggested, but strictly not recommended solution by Harry .col-fixed(@size, @count, @wrapper) { & when ((@size*@count) <= @wrapper) { width: unit(@size, px); margin-right: unit( (@wrapper - @count * @size) / (@count - 1), px); } & when ((@size*@count) > @wrapper) { /* there is no such variable and hence when the...

How to rewrite this C# code

f#

Aside from Patryk's point on comment: It's a really imperative problem so it will not get much prettier. The only thing I would try to change is the repeated read/writes - maybe like this: let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) = let bufferLen : int = 4096 let...

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

dictionary,f#,converter,record

In practice, the best advice is probably to use some existing serialization library like FsPickler. However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go. The following takes a record and creates a map from string...

setting objects equal to eachother (java)

java,methods,compiler-errors,equals

There are two ways to interpret "set the objects equal to each other". One is that you want p1 and p3 to refer to the same object. Like how Clark Kent and Superman are two names (references) for the same person. This would be accomplished by: Person p1 = new...

Can someone help me fix this error in Swift "Apple Mach-O Linker Error?

ios,xcode,swift,compiler-errors

Click on Build Settings and under Library Search Paths, delete the paths.

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

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

How to handle Arithmetic operation OverflowException in F#?

python,f#

You should use bigint for large numbers, like this [1I..1234567I] |> List.filter (fun x -> x % 3I * x % 5I = 0I) |> List.sum or (less readable) [bigint 1..bigint 1234567] |> List.filter (fun x -> x % bigint 3 * x % bigint 5 = bigint 0) |>...