Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Type inference woes

Name: Anonymous 2019-01-25 15:56

CONSIDER this Rust code that a reasonable human being might try to write:

fn add<T>(a: T, b: T) -> T {
return a + b;
}

If you try to compile that, you’ll get an error like this:

:1:25: 1:30 error: binary operation `+` cannot be applied to type `T`
What you actually have to write is something like this:

use std::ops::Add;
fn add<T: Add>(a: T, b: T) -> T::Output {
return a + b;
}

Now it typechecks correctly.

This seems a little ridiculous. The compiler already knew that T had to be a type that supports addition — it just told me that. So why am I spelling it out?

Name: Anonymous 2019-01-26 12:31

>>7
Importing library modules has nothing to do with type inference. This whole thread is about a mental midget complaining why the compiler throws an error on his incorrect type definition. Literally every single language with type inference will throw the same error.

Mental midgetry:
import Prelude ((+))

test :: a -> a -> a
test x y = x + y


• No instance for (GHC.Num.Num a) arising from a use of ‘+’
Possible fix:
add (GHC.Num.Num a) to the context of
the type signature for:
test :: forall a. a -> a -> a
• In the expression: x + y
In an equation for ‘test’: test x y = x + y

Type inference is about the typed being inferred, test x y = x + y without any type declaration works just fine for example.

Here is the fix for the first one:
import Prelude ((+), Num)

test :: Num a => a -> a -> a
test x y = x + y

Surprisingly similar, huh?

In any case, rust advertises type inference ONLY for the code inside a function - not for its arguments and return types.

>>11
What? I am pretty sure that traits can do the same in rust.

>>12
Why would you put spaces between your type variables?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List