Zulip Chat Archive

Stream: lean4

Topic: Rank-polymorphic fmap on Lists


Ioannis Konstantoulas (Sep 16 2023 at 17:15):

This question came up in a recent Lean thread on HN. A user asked if Lean supports list comprehensions; the main motivation is as follows: with list comprehensions, for a k-ary function, the notation

[ Function Arguments | arg_1 <-List_1 ... arg_k List_k ]

works irrespective of the "rank" k; this is very convenient for numerical functions with many arguments. Do we have something like this? If not, is it easy to code such variadic notation?

Adam Topaz (Sep 16 2023 at 17:19):

You can do this with do notation quite easily, I think…

Ioannis Konstantoulas (Sep 16 2023 at 17:21):

It is definitely doable, but a one-liner polymorphic notation would be much nicer. By the way, I yanked the terminology "rank polymorphism" from array languages, and the programmers using them have excellent arguments for its utility.

Adam Topaz (Sep 16 2023 at 17:23):

import Mathlib.Data.List.Basic

example (L1 L2 L3 : List ) (f :       α) : List α := do
  let a  L1
  let b  L2
  let c  L3
  return f a b c

Adam Topaz (Sep 16 2023 at 17:24):

You can put those on one line with ; if you really want a one-liner.

Eric Wieser (Sep 16 2023 at 17:25):

(to be clear, that is (do let a ← L1; let b ← L2; let c ← L3; return f a b c))

Eric Wieser (Sep 16 2023 at 17:26):

Though you can also write the even shorter do return f (← L1) (← L2) (← L3) which de-sugars to the above

Adam Topaz (Sep 16 2023 at 17:27):

Even this works:

example (L1 L2 L3 : List ) (f :       α) : List α :=
  return f ( L1) ( L2) ( L3)

Adam Topaz (Sep 16 2023 at 17:28):

Lean4 is magic.

James Gallicchio (Sep 16 2023 at 17:28):

note that this does only work for List, while the do for-in notation works for lots more types. but there are generic ways to get the same List-like behavior with other types, it just requires mac's itertools or my leancolls :P

Eric Wieser (Sep 16 2023 at 17:31):

@Adam Topaz, what's going on with the lack of do there?

Adam Topaz (Sep 16 2023 at 17:33):

return does more than just pure

James Gallicchio (Sep 16 2023 at 17:35):

i don't know if it's .. desirable.......... that the one without do works, but it's certainly interesting that it does!

Ioannis Konstantoulas (Sep 16 2023 at 17:45):

The return trick is fantastic.

Mario Carneiro (Sep 16 2023 at 22:42):

James Gallicchio said:

i don't know if it's .. desirable.......... that the one without do works, but it's certainly interesting that it does!

Desirability aside, it is deliberate, return is a term constructor that automatically acts like do return

Jannis Limperg (Sep 18 2023 at 09:34):

FYI, return also short-circuits. E.g. a return in a for loop ends the loop. So it's really more like C's return than Haskell's.


Last updated: Dec 20 2023 at 11:08 UTC