Zulip Chat Archive

Stream: Is there code for X?

Topic: Monadic operations inside List.takeWhile


Jeremy Salwen (May 09 2023 at 20:31):

I am relatively new to functional programming, so maybe there is a trick here I am missing, but it seems like there is no way to use monadic functions as the condition in List.takeWhile?

I wrote the following function that works for me instead.

def List.takeWhileM {m : Type  Type} [Monad m]  {α} (p : α  m Bool) : List α  m (List α)
| [] => pure []
| (x :: xs) => do
  if  p x then
    do let ys  takeWhileM p xs
       pure (x :: ys)
  else
    pure []

But I was wondering if there is a standard way of doing this?

Scott Morrison (May 09 2023 at 23:00):

It seems to not exist yet (there is ListM.takeWhileM for monadic lazy lists). You could PR it!

Scott Morrison (May 09 2023 at 23:02):

You could inline the let.

Scott Morrison (May 09 2023 at 23:02):

And I think for consistency with other APIs you would have p : α → m (ULift Bool), so m can be universe polymorphic.

Jeremy Salwen (May 10 2023 at 04:43):

Scott Morrison said:

It seems to not exist yet (there is ListM.takeWhileM for monadic lazy lists). You could PR it!

To std, or mathlib?

Mario Carneiro (May 10 2023 at 04:44):

the std version would probably not be universe polymorphic if that means adding a ulift

Eric Wieser (May 10 2023 at 08:20):

Does std not have access to ulift?

Mario Carneiro (May 10 2023 at 19:26):

no, it's just a more awkward interface and I think that core usually doesn't do universe parametricity unless it is zero cost


Last updated: Dec 20 2023 at 11:08 UTC