FAQ Database Discussion Community


Can function type be defined by inference?

function,scala,type-inference
Scala type inference is really nice and it is easy to get used not to have to write things twice. The more it hurts when you have to. One such example are function types. Sometimes I would like to create a named type for some function signature. Is it possible...

Can java infer the generic type from a class defined on top of generics?

java,generics,type-inference,nested-generics
I've borrowed the code from this other answer interface IConverter<TFrom, TTo> { TTo convert(TFrom from); } class IntToStringConverter implements IConverter<Integer, String> { public String convert(Integer from) { return "This is a string: " + from.toString(); } } class ConverterUser<TConverter extends IConverter<TFrom, TTo>, TFrom, TTo> { public ConverterUser() { } private...

Why doesn't type inference work in this case

java,generics,type-inference
I want to write a comparator which sorts objects having a parameter of type Number. I created a generic dto as follows public class GenericSortingDTO<T extends Number> { private T parameter; public T getParameter() { return parameter; } public void setParameter(T parameter) { this.parameter = parameter; } } I created...

In Scala, why `_` can't be used in groupBy here?

scala,functional-programming,type-inference
I am trying to calculate the occurrence list of each character in a word, my current codes looks like this: "hello" .groupBy((x:Char)=>x) .map(a=>(a._1, a._2.length)) I think the .groupBy((x:Char)=>x) looks clumsy and therefore rewrite like this: "hello" .groupBy(_) .map(a=>(a._1, a._2.length)) But then the compiler throw an error Error:(1, 18) missing parameter...

Why isn't Scala picking the most specific instance in this this type class?

scala,type-inference,typeclass
I am struggling to build this computation pipeline builder in Scala. I want a class that has two methods, map and reduce, that receive anonymous functions in a "fluent interface". These functions will be composed, so I want to type-check all of them, also having their input type inferred from...

How to read data from Excel starting from given row and getting proper type inference

.net,excel,datatable,ado,type-inference
I am importing data from .xls and .xlsx files using these connection strings "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\file.xls;Extended Properties="Excel 8.0;HDR=YES;IMEX=0;MaxScanRows=16;Empty Text Mode=NullAsEmpty;" or "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=0;MaxScanRows=16;Empty Text Mode=NullAsEmpty;" I load data in a datatable. Using connection As New OleDbConnection(connString) connection.Open() wsName = "myWorksheet$" Dim SQL As [String] =...

Why can't I remove the Ord Typeclass from this haskell implementation of Kadane's algorithm?

algorithm,haskell,types,type-inference,type-systems
I have been implementing kadane's algorithm in haskell, AFAIK it is working correctly kadane' :: (Ord a, Num a) => [a] -> a kadane' xs = head$ foldl maxsub [0,0] xs maxsub :: (Ord a, Num a) => [a] -> a -> [a] maxsub x y | last(x)+y > head(x)...

Why doesn't overload resolution work here?

c#,generics,covariance,type-inference,method-overloading
Consider this snippet: var bytes = new byte[] {0, 0, 0, 0}; bytes.ToList().ForEach(Console.WriteLine); This will result in the compile time error: No overload for 'System.Console.WriteLine(int)' matches delegate 'System.Action<byte>' You can declare a lamdba as a workaround, bytes.ToList().ForEach((b => Console.WriteLine(b))), but why doesn't overload resolution work in the first case? ...

OCaml: type inference with polymorphic variants

ocaml,type-inference
Function f argument type is [< 'A | 'B] that's what I want. # let rec f = function | `A -> 0 | `B -> let _ = f in 1 ;; val f : [< `A | `B ] -> int = <fun> However, if I call it...

FSharp: Type inference with generic

generics,f#,type-inference
I do not understand why the following code does not compile module GenericsTest = open System type Dog = { name:string } type Apple = { size:int } let get<'a> (id:string) = Activator.CreateInstance<'a>() let creatorInferred getAsParam = let apple = { name = getAsParam "some-apple" } let dog = {...

In scala, why doesn't lower bound work well here?

scala,generics,types,functional-programming,type-inference
These codes compiles well: abstract class CodeTree case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree case class Leaf(char: Char, weight: Int) extends CodeTree def weight(tree: CodeTree): Int = tree match { case Fork(left, right, chars, weight) => weight case Leaf(char, weight) => weight } def insert_orderedCodeTreeList[T...

Why can't I define the following CoFixpoint?

ocaml,type-inference,coq,induction,coinduction
I am using: $ coqtop -v The Coq Proof Assistant, version 8.4pl5 (February 2015) compiled on Feb 06 2015 17:44:41 with OCaml 4.02.1 I defined the following CoInductive type, stream: $ coqtop Welcome to Coq 8.4pl5 (February 2015) Coq < CoInductive stream (A : Type) : Type := Coq <...

Why Scala does not have a decltype?

scala,type-inference,decltype
Sometimes one might want to declare x to be of the same type as y. With vals type inference handles this very well, but this does not work in some other areas, like with function types. A solution which seems obvious to a programmer with some C++ experience would be...

Getting over type parameter bounds error with type checked by TypeTag

scala,reflection,type-inference,type-erasure
I think I am close to start understanding type erasure and the Scala reflection API. But I'm still in a world of pain... How do I deal with this problem? I have a class that can take generic functions as arguments, and I need to do different things depending on...

Java type inference: reference is ambiguous in Java 8, but not Java 7

java,generics,compiler-errors,java-8,type-inference
Lets say we have 2 classes. An empty class Base, and a subclass of this class Derived. public class Base {} public class Derived extends Base {} Then we have a few methods in another class: import java.util.Collection public class Consumer { public void test() { set(new Derived(), new Consumer().get());...

Type inference inconsistency between toList and toBuffer

scala,type-inference
As per the example below, calling xs.toList.map(_.toBuffer) succeeds, but xs.toBuffer.map(_.toBuffer) fails. But when the steps in the latter are performed using an intermediate result, it succeeds. What causes this inconsistency? scala> "ab-cd".split("-").toBuffer res0: scala.collection.mutable.Buffer[String] = ArrayBuffer(ab, cd) scala> res0.map(_.toBuffer) res1: scala.collection.mutable.Buffer[scala.collection.mutable.Buffer[Char]] = ArrayBuffer(ArrayBuffer(a, b), ArrayBuffer(c, d)) scala>...

Generic F# operators fun

generics,f#,type-inference
This question follows the idea posted here: Generic units in F# I've started wondering if that was possible to define a generic operator that accepts two arguments in a similar way, like it it presented in the post I linked ? For exapmple: I've been trying to implement an "AlmostEqual"...

Type Inference in Haskell v. Scala

scala,haskell,type-inference
Given the following code: Prelude> let f x = if (x) then 55 else "foo" Why does the compiler look for a Num [Char]? <interactive>:2:23: No instance for (Num [Char]) arising from the literal `55' In the expression: 55 In the expression: if (x) then 55 else "foo" In an...

Haskell strange type inference narrowing [duplicate]

haskell,ghc,type-inference,ghci
This question already has an answer here: Type inference of a function in GHCi differs with loaded from a file 1 answer GHCi 7.8.3 filter (\(a,b) -> a>0) :: (Ord a, Num a) => [(a, t)] -> [(a, t)] as expected ^ fstGt0 xs = filter (\(a,b) -> a>0)...

Strange Swift numbers type casting

swift,casting,type-inference
I've just noticed that Swift does some type casting over Int and Double. When I try to evaluate (10 / 3.0) - (10 / 3) 0.333... is expected, but it's actually 0.0. Could someone explain this please?...

How to get generic field type (string representation) with help reflection - Java?

java,reflection,types,type-inference
There are some fields: public class Class1 { private Map<String,Integer> field1 = new HashMap<String,Integer>(); private int someField = 1; private int[] myIntArray = new int[]{1,2,3}; private List<ArrayList<String>> words = null; private ArrayList<String>[] group = (ArrayList<String>[])new ArrayList[4]; private List<List<List<ArrayList<List<List<String>>>>>> lists = null; } Is there a simple way to get string...

How can I call this generic function?

swift,generics,protocols,type-inference
I just thought of this trying to figure out Swift generics. I have come up with the following test code where I'd like to call f(). I can't figure out how I can tell the compiler that the T is Classy in this case. protocol Prot { func doSomething() static...

In Scala, how to use `Nothing` as returned value to Fake a method?

scala,testing,functional-programming,mocking,type-inference
I'd like to create a method called save and haven't been ready to implement it. However, I don't want it to throw exceptions during evaluated. So I tried to make it return a Nothing as the result. def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = { // To be done new...

Why doesn't this Java 8 stream example compile?

java,java-8,type-inference,java-stream
I'm trying to figure out why this code does not compile on JDK 1.8.0_45: public class Example<E extends Example<E>> { public List<? extends Example<?>> toExamples(Collection<String> collection) { return collection.stream() .map(v -> lookup(v)) .collect(Collectors.toList()); } public static <E extends Example<E>> E lookup(String value) { return null; } } Adding a seemingly...

Infinite loop seems to confuse Scala's type system

scala,infinite-loop,type-inference,return-type
Here is an artificial toy example that demonstrates my problem: def sscce(): Int = { val rand = new Random() var count = 0 while (true) { // type mismatch; found: Unit, required: Int count += 1 if (rand.nextInt() == 42) return count } } How can I help the...

F# type inference less generic than indicated by the type annotations

generics,f#,type-inference
In the last line of the following code snippet, I get two warnings: This construct causes code to be less generic than indicated by the type annotations. The type variable 'c has been constrained to be type ''a'. and This construct causes code to be less generic than indicated by...

C# Type Inference fails with methods that contain default parameters

c#,type-inference
Say I have the following method: static int MethodWithDefaultParameters(int a, int b=0, int c=1) { return a + b + c; } And then I use this method in a LINQ query like so: Enumerable.Range(1,10).Select(MethodWithDefaultParameters); This fails with: Error 1 The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred...

Can't infer type in generic tostring method C#

c#,types,type-inference
I have a custom facilitator method that takes a value, and determines its type. If it's a data structure such that it can be enumerated over, then it gets passed to its respective ToString method to be printed out. But if not, then it's builtin .ToString() method is called. public...

How to change from which argument is the type inferred in generic methods?

c#,generics,lambda,type-inference,linq-expressions
Suppose there's a static method in my Utils class, that sets the value of a property. public static SetPropertyValue<TDest, TVal> (Expression<Func<TDest, TVal>> expression, TDest destination, TVal value) { // ... } Additionally, there is a class: public class DataObject { public short Code { get; set; } } And the...

Is it possible to get the infinite kind error in Haskell 98?

haskell,functional-programming,ocaml,type-inference,unification
I am implementing a kind system for a new functional programming language and I am currently writing the function to unify two kinds. There are four cases two consider: +---------+---------+-------------------------------------------------------+ | k1 | k2 | action | +=========+=========+=======================================================+ | var | var | k1 := k2 ^ k2 := k1...

Why method of class does not have access to some field of my class?

c++,templates,c++11,smart-pointers,type-inference
I try to implement linked_ptr. It is a study task. It is a part of my code: template <class T> class linked_ptr { public: //*************** linked_ptr<T>(linked_ptr<T> const& other) { p = other.p; left_ptr = &other; right_ptr = other.right_ptr; if (other.right_ptr != nullptr) { (other.right_ptr)->left_ptr = this; } other.right_ptr = this;...

Generic artihmetical operations on generic types in F#

generics,f#,type-inference
I found a nice article: http://nut-cracker.azurewebsites.net/blog/2011/08/09/operator-overloading/ and decided to play a bit with F# using the information presented in the article. I created my own type Vector2D<'a>, supporting addition and multiplication by a constant: type Vector2D<'a> = Vector2D of 'a * 'a with member this.X = let (Vector2D (x,_)) =...

Inferring template parameters

c++,templates,type-inference
I am attempting to write a function-template that infers most of its parameters for the purpose of a simple lookup table. However, my efforts consistently get compiler errors. Here is my best attempt so far: // A simple templated struct that maps one key to one value template<typename KT, typename...

Implementing simple type inference

c,type-inference
How do I implement basic type inference, nothing fancy just for inferring if the given value is an integer, double, or float. For instance, if I had a token for each type WHOLE_NUMBER, FLOAT_NUMBER, DOUBLE_NUMBER, and I had an expression like 4f + 2 + 5f, how would I deduce...