3
$\begingroup$

first time user and not quite familiar with how to enter my code here properly, but this isn't lengthy..

I have a previously defined function that computes the total time it takes to ride a bike with given parameters distance and speed..

Clear[biketime, distance, speed]
biketime[distance_, speed_] :=  distance/speed

So biketime[10,2] would refer to 5 (minutes)

Now, what if I wanted to pass a list into this function using replacement rules? I have given an attempt which now looks like:

Clear[biketime, distance, speed, list]
biketime[distance_, speed_] :=  distance/speed
totaltime[list_] := list /. List -> Plus[ biketime[distance, speed]]
totaltime[{10, 2}, {15, 3}] 

All I get as an output is totaltime[{10,2 }, {15, 3}], when I want the output to be those 2 pieces of data added together, so my output would be 10... Either something isn't defined properly or I'm just completely wrong and the function isn't doing what I think it is doing in my head.

Any suggestions? Sorry about the messy code.

$\endgroup$
2

1 Answer 1

4
$\begingroup$

If you are going supply the arguments as pairs; i.e., as lists of the form {arg1, arg2}, the easiest implementation is define bike time to take a pair as its single argument and let Mathematica use its pattern matching capabilities to pull out the distance and speed from the argument. (This is sometimes called argument destructuring and can be very useful in many applications.)

I urge you to read the documentation article Introduction to Patterns. Use the Search and Replace dialog to search for "destructuring"

Clear[biketime]
biketime[{distance_, speed_}] := distance/speed

Note: The formal arguments, distance and speed, do not have to cleared at top-level; they do not get top-level values when SetDelayed ( := ) is used to define the function.

With the above definition, I think most experienced Mathematica users would write

biketime /@ {{10, 2}, {15, 3}} // Total

10

to get the total time for the two sets of arguments. Of course, the list of argument pairs can be of any length.

The above uses some keyboard shortcuts that you will want to learn. The long form for the expression is:

Total[Map[biketime, {{10, 2}, {15, 3}}]]

so Map and Total are functions you might want to look at.


Plus @@ (biketime /@ {{10, 2}, {15, 3}})

will also work, where @@ is the short form of Apply.

$\endgroup$
1
  • $\begingroup$ Very informative and thanks for the link! $\endgroup$
    – Brandon
    Oct 7, 2016 at 0:12

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.