4
$\begingroup$

I have a list consisting of DateObjects and strings:

lis = {DateObject[{2019, 1, 1}], "a", "b", DateObject[{2019, 1, 2}], "c", "d", "e", DateObject[{2019, 1, 3}], "f"};

I would like to construct a function that takes as its argument a DateObject, and have it return all the following string elements that follow it in lis until the next occurrence of a DateObject in the list.

If the argument is DateObject[{2019,1,2}], then the return would be:

res = {"c","d","e"}

There probably are many ways to do this. I tried using SplitBy[lis, DateObjectQ] then SequenceCases but no luck.

$\endgroup$
5
$\begingroup$
SequenceCases[lis, {DateObject[{2019, 1, 2}], a:Except[_DateObject] ..., _DateObject} :> a]

{"c", "d", "e"}

Also

Cases[lis,
  {___, DateObject[{2019, 1, 2}], a : Except[_DateObject] ..., _DateObject, ___} :> a, All]

{"c", "d", "e"}

$\endgroup$
2
$\begingroup$
f[data_List, d_DateObject] := Append[data, d -> {}]
f[{dates___, d_ -> l_List}, s_String] := {dates, d -> Append[l, s]}
lookup = Fold[f, {}, lis]

Mathematica graphics

We can now use this lookup like this:

Mathematica graphics

{"c", "d", "e"}

$\endgroup$
2
$\begingroup$
lis = {
   DateObject[{2019, 1, 1}], "a", "b",
   DateObject[{2019, 1, 2}], "c", "d", "e",
   DateObject[{2019, 1, 3}], "f"};

f[x_] := Rest[FirstCase[Split[lis, Head[#2] =!= DateObject &], {x, ___}]]

res = f[DateObject[{2019, 1, 2}]]

{"c", "d", "e"}

$\endgroup$
2
$\begingroup$

Straight forward solution:

dateExtract[date_DateObject, lis_List] :=
    FirstPosition[lis, date] //
    Drop[lis, First@#] & //
    TakeWhile[#, Not@*DateObjectQ] &
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.