Zulip Chat Archive

Stream: general

Topic: Appending an option to a list


Eric Wieser (Jun 20 2024 at 21:26):

Does this function have a name somewhere?

def cons? {α} (l : List α) : Option α  List α
  | none => l
  | some a => a :: l

Can I get it without a match with some monad transform?

Mauricio Collares (Jun 21 2024 at 13:26):

Is (·.toList ++ l) cheating?

Damiano Testa (Jun 21 2024 at 13:40):

Is (a::l.map some).reduceOption cheating?

Chris Bailey (Jun 21 2024 at 13:41):

What's wrong with the match?

Adam Topaz (Jun 21 2024 at 13:42):

Is if let some a := x then a :: l else l cheating?

Mauricio Collares (Jun 21 2024 at 13:56):

Damiano Testa said:

Is (a::l.map some).reduceOption cheating?

This one's linear time, I think. At least

def main := do
  let l := List.replicate 10000000 1
  for i in [1:1000] do
    IO.println <| List.take 100 <| cons? l (some i)

is slow.

Marcus Rossel (Jun 21 2024 at 14:10):

Is a.elim l l.conscheating?

Chris Bailey (Jun 21 2024 at 14:28):

Final offer: (a.map xs.cons).getD xs

Kyle Miller (Jun 21 2024 at 17:25):

Mauricio's is nice for mentioning each variable just once.

Here's a similar one for fun, but won't win in golf.

def cons? {α} (x? : Option α) : List α  List α := (x?.map List.cons).getD id

Last updated: May 02 2025 at 03:31 UTC