3
$\begingroup$

In

Block[{ ds = Dataset[{
     <|"task" -> "task4", "parents" -> "parent1", 
      "start" -> "2019-05-14 17:10", "end" -> "2019-05-14 17:15", 
      "utility" -> "0.9"|>}
    ],
  hrAssociation = 
   KeySort[Merge[
     Rule @@@ 
       Flatten[GroupBy[
           ds[All, <|"d" -> (DateObject /@ {#"start", #"end"})|> &], 
           First -> Last, 
           Map[{CurrentDate[#[[1]], "Day"], 
              DateDifference[#[[1]], #[[2]], "Hour"]} &]] // Normal // 
         Values, 1] // Sort, Total]]},
 hrAssociation
 ]

I get

enter image description here

and I think it's because I'm referring to the first dataset variables (ds) deep within the second variable (hrAssociation). How to fix?

I have tried replacing Block with With and Module and the problem persists.

$\endgroup$
5
$\begingroup$

This works:

Module[{ds,hrAssociatio}
    ,
     ds = Dataset[{
         <|"task" -> "task4", "parents" -> "parent1", 
          "start" -> "2019-05-14 17:10", "end" -> "2019-05-14 17:15", 
          "utility" -> "0.9"|>}
        ]
    ;  hrAssociation = 
       KeySort[Merge[
         Rule @@@ 
           Flatten[GroupBy[
               ds[All, <|"d" -> (DateObject /@ {#"start", #"end"})|> &], 
               First -> Last, 
               Map[{CurrentDate[#[[1]], "Day"], 
                  DateDifference[#[[1]], #[[2]], "Hour"]} &]] // Normal // 
             Values, 1] // Sort, Total]
        ]
    ; hrAssociation
    ]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ I see that this works, but why is my code wrong? Is it a bug in Mathematica or a conceptual error I'm making? $\endgroup$ – George Dec 21 '19 at 21:05
  • 1
    $\begingroup$ It's a conceptual error. Assignments happen first, before the scoping occurs. The scoped arguments are only in the second block. $\endgroup$ – b3m2a1 Dec 21 '19 at 21:31
4
$\begingroup$

To add to Rolf's answer, if you need this in the body of the declaration you can use :=

Block[{ds = 
   Dataset[{<|"task" -> "task4", "parents" -> "parent1", 
      "start" -> "2019-05-14 17:10", "end" -> "2019-05-14 17:15", 
      "utility" -> "0.9"|>}
    ],
  hrAssociation :=
   KeySort[
    Merge[
     Rule @@@
       Flatten[
        GroupBy[
           ds[All, <|"d" -> (DateObject /@ {#"start", #"end"})|> &], 
           First -> Last, 
           Map[{CurrentDate[#[[1]], "Day"], 
              DateDifference[#[[1]], #[[2]], "Hour"]} &
            ]
           ] // Normal // Values, 1] // Sort,
     Total
     ]
    ]
  },
 hrAssociation
 ]
|improve this answer|||||
$\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.