1
$\begingroup$

My understanding is that for nesting pure functions, one should use the explicit version of pure functions. I would like to know the best way of making it readable for people.

I currently have defined a function that takes a list of points pp, and a single point p as input and returns a point from pp that is nearest to point p.

I have defined it as:

FindNearestPointToPoint[
pp_List?(MatrixQ[#,NumericQ]&),
p_List?(VectorQ[#,NumericQ]&)]/; 
Last[Dimensions[pp]]==Length[p] 
:=MinimalBy[pp,Function[PP,(PP-p).(PP-p)]]

FindNearestPointToPoint[{{1, 2}, {1, 3}, {1, 5}}, {1, 10}]=
(*{{1, 5}}*)

What it does is, it calculates the distance between p and each point in pp and chooses the one with the shortest norm.

Now, as the next step I want there to be multiple p points and change the choice criterion to be one involving multiple points. I have currently opted for the following:

FindNearestPointToPoints(
pp_List?(MatrixQ[#, NumericQ] &), 
p_List?(MatrixQ[#, NumericQ] &)] /; 
Last[Dimensions[pp]] == Last[Dimensions[p]] :=
MinimalBy[
    Function[PP,
            Total[
                  Map[
                       Function[P, (PP - P).(PP - P)]
                       , p]
            ]
    ]
]
FindNearestPointToPoints[{{1, 2}, {1, 3}, {1, 5}}, {{1, 10}, {1, 9}}]=
(*{{1,5}}*)

Now, pp and p might not be the ideal names for the original function's variables, but I would be interested to know if there is a variable naming convention for nested functions of this type.

Also would like to know if these nested functions can be made more readable and or efficient, or if there is any way of avoiding explicit Function[]s.

$\endgroup$
  • 1
    $\begingroup$ Underscores are... special in Mathematica. (Highlight one, press F1, see what I mean.) You don't really use them in function names like you did here. $\endgroup$ – J. M.'s technical difficulties Feb 18 '16 at 1:11
  • $\begingroup$ @J.M. erm what underscores? I am using those for pattern matching $\endgroup$ – Shb Feb 18 '16 at 1:13
  • 1
    $\begingroup$ Also, take a look at Nearest[ ] $\endgroup$ – Dr. belisarius Feb 18 '16 at 1:14
  • 3
    $\begingroup$ @Shb Try to paste here your actual code. You'll shorten the write-read-comment-update by ten times (from my experience :) ) $\endgroup$ – Dr. belisarius Feb 18 '16 at 1:17
  • 2
    $\begingroup$ FindNearestPointToPoints[a_, b_] := a[[Ordering[Tr /@ Outer[(#1 - #2).(#1 - #2) &, a, b, 1], 1]]] $\endgroup$ – Dr. belisarius Feb 18 '16 at 4:13