#Type inference on a tuple piped to an anonymous fn

1 messages · Page 1 of 1 (latest)

frail rock
#
pub fn foo() -> String {
  #("gleam")
  |> fn(x) { x.0 }
}

Gives:

1  │   |> fn(x) { x.0 }
   │              ^ What type is this?

To index into a tuple we need to know it size, but we don't know
anything about this type yet. Please add some type annotations so
we can continue.

Could the type inference potentially work in this case, or is there some other issue/consideration?

smoky light
#

Have you given an explicit type to the argument?

#

I tried giving an explicit type on the lambda and it works, at least on the tour.

rancid fox
#

You certainly can, they are asking if the compiler could do that for them

#

It seems like something which should be possible, but I don't know the type inference system that well

charred orchid
#

If i understand correctly, a function only infer types based on its body, not how it is invoked

rancid fox
#

No, that's not correct

#

Actually, maybe it is

charred orchid
#

Ah, ok. How does it work then

rancid fox
#

I was going to give this example:

pub fn identity(x) {x}

pub fn main() {
  let a = 1
  let b = identity(a)
}
#

But the type of x just gets inferred to a type variable

#

So yeah you're probably right

charred orchid
rancid fox
#

Yes

charred orchid
#

Which is determined at the time of function creation

rancid fox
#

Ah wait, I think I've found a case

#
pub fn apply(x: Int, f: fn(Int) -> Int) -> Int {
  f(x)
}

pub fn main() {
  apply(1, fn(a) { a })
}
#

The type of a is correctly inferred to be Int

#

So it's not 100% from the body of the function

#

But honestly not sure how deep it goes, I haven't really touched that side of the compiler

charred orchid