6
$\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 Answers 5

6
$\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$
5
$\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$
4
$\begingroup$

Straight forward solution:

dateExtract[date_DateObject, lis_List] :=
    FirstPosition[lis, date] //
    Drop[lis, First@#] & //
    TakeWhile[#, Not@*DateObjectQ] &
$\endgroup$
3
$\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$

We can easily build a lookup - table with

look = 
  GroupBy[Split[lis, MatchQ[#2, _String] &],
  First -> Rest, 
  Flatten];

and then ask for

look[DateObject[{2019, 1, 2}]]

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

Alternatively, we can use Lookup:

Lookup[look, DateObject[{2019, 1, 3}], {}]

{"f"}

With a small change of the grouping argument

look = 
  GroupBy[Split[lis, MatchQ[#2, _String] &], 
  First @* First -> Rest,
  Flatten]

we could more comfortably ask:

look[{2019, 1, 2}]

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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