3
$\begingroup$

To explain better what I mean I'll give an example of what I want the symbol to do. I want a symbol that wraps around a unit vector to use it as head for further calculations.

Something like:

UnitVector[{1,0,0}]
UnitVector[{1,1,0}]
(* UnitVector[{1,0,0}] *)
(* $Fail *)

so after I can use it in a function like:

RandomStuff[arg_UnitVector]:=(* Some procedure that requires the argument to be a unit vector *)

I know this can be easily done with a wrapper function that just returns a UnitVector, but I would also like to know how to do this and if it is considered a good or bad practice.

New contributor
AmadoC is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
$\endgroup$
3
  • 1
    $\begingroup$ Probably it should be something like this mathematica.stackexchange.com/a/79891/82074 but without all the fancy box stuff. $\endgroup$
    – AmadoC
    Commented yesterday
  • 1
    $\begingroup$ Normally I would do something like unitVectorQ[v_?VectorQ] := TrueQ@Simplify[Norm[v] == 1]; unitVectorQ[_] := False; f[arg_?unitVectorQ] := (*etc*). I can't call to mind a use-case in which having a wrapper head on a standard sort of object like a vector would be convenient. I imagine my code would have to check, add, and remove the wrapper all the time. (Compare for example all the complaints on this site gets about MatrixForm.) $\endgroup$
    – Michael E2
    Commented yesterday
  • $\begingroup$ Thanks, I over simplified my use case from what I really want to do. My problem is that I need to write vectors in two different notations, one is something like an SparseArray but with a different coodinate system and an standard vector. The first one is easier to write as user and the second one is easier to operate, that is why I want a head wraper. $\endgroup$
    – AmadoC
    Commented 22 hours ago

1 Answer 1

4
$\begingroup$

As suggested in the comments you first need a validation function, something like

unitVectorQ[l:{_,_,_}] := SameQ[Norm[l], 1]
unitVectorQ[___] := False

Then write one down value for unitVector

unitVector[in_ /; !unitVectorQ[in]] := $Failed

and it works as expected

In[101]:= unitVector[{1, 0, 0}]

Out[101]= unitVector[{1, 0, 0}]

In[102]:= unitVector[{1, 1, 0}]

Out[102]= $Failed

Now you are guaranteed anything wrapped in unitVector is really a 3-dimensional unit vector.

$\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.