0
$\begingroup$

Two questions. I have created a sample problem, and would be glad to have your help.

I have 2 functions, fun1 and fun2, and one of the function is the attribute of the other function. My function fun2 works fine as long as fun1 isn't a function involving a dataframe

fun1[i_] := i + 1
fun2[i_] := Module[{x}, x = (Table[i, {k, 1, 2}])]

fun2[fun1[k]]
(*Out[710]= {2, 3}*)

Now, lets create a sample dataframe and use it as an attribute:

dataset =  Dataset[{<|"a" -> 1, "b" -> "x", "c" -> {1}|>, <|"a" -> 2, 
"b" -> "y", "c" -> {2, 3}|>, <|"a" -> 3, "b" -> "z", 
"c" -> {3}|>, <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>, <|"a" -> 5,
 "b" -> "y", "c" -> {5, 6, 7}|>, <|"a" -> 6, "b" -> "z", 
"c" -> {}|>}]

The output I get is:

fun2[dataset[k]]
(*Out[711]={1[{<|"a" -> 1, "b" -> "x", "c" -> {1}|>, <|"a" -> 2, "b" -> "y", 
"c" -> {2, 3}|>, <|"a" -> 3, "b" -> "z", "c" -> {3}|>, <|"a" -> 4,
 "b" -> "x", "c" -> {4, 5}|>, <|"a" -> 5, "b" -> "y", 
"c" -> {5, 6, 7}|>, <|"a" -> 6, "b" -> "z", "c" -> {}|>}],  2[{<|"a" -> 1, "b" -> "x", "c" -> {1}|>, <|"a" -> 2, "b" -> "y", 
"c" -> {2, 3}|>, <|"a" -> 3, "b" -> "z", "c" -> {3}|>, <|"a" -> 4,
 "b" -> "x", "c" -> {4, 5}|>, <|"a" -> 5, "b" -> "y", 
"c" -> {5, 6, 7}|>, <|"a" -> 6, "b" -> "z", "c" -> {}|>}]}*)

But, I am expecting more like:

Table[dataset[k], {k, 1, 2}]

So what might be the problem here?

My second question is, is there any way the func2 can be written such that it sets the Table index k corresponding to the index of func1[k]? Say even if I give fun1[k1] as an input func2[fun1[k1]] still spits out (*Out[710]= {2, 3}*)

$\endgroup$

1 Answer 1

1
$\begingroup$

Here's my understanding of the semantics of your situation. You have the list {1,2} that you want to treat as a sort of index into other functions. I.e. for some other function g, you want a function that will produce {g[1],g[2]} and will do this generically with any (appropriately defined) such g.

Assuming that's correct, there are built-in constructs that you could use. For example, Map:

g/@{1,2}
(* {g[1], g[2]} *)

Or to use your examples:

fun1 /@ {1, 2}
(* {2, 3} *)

dataset /@ {1, 2}
(* gives the first two rows as elements of a list *)

You could, of course, define your own function that uses Map:

fun2[fn_] := fn /@ {1, 2};
fun2[fun1]
(* {2, 3} *)
$\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.