Skip to content

Instantly share code, notes, and snippets.

@tralston
Created May 19, 2018 00:12
Show Gist options
  • Save tralston/24ad7800b1ad578793b17b3d0bf5a727 to your computer and use it in GitHub Desktop.
Save tralston/24ad7800b1ad578793b17b3d0bf5a727 to your computer and use it in GitHub Desktop.
[Constrain functions to specific unit types] #mathematica
f[x_]:=x
f[5] ==> 5
f[x: Quantity[_, unit_]?(CompatibleUnitQ[#, "feet"] &)]:=x (* Important that parameters in list do not have underscore *)
f[5] ==> f[5]
f[Quantity[5, "feet"]] ==> 5 ft
f[Quantity[5, "meters"]] ==> 5 m
f[Quantity[5, "pound"]] ==> f[5 lb]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment