How can I/should I pass a single sequence as an argument to a function which expects multiple arguments? Specifically, I'm trying to use cartesian-product and pass it a sequence (see below); however, when I do so the result is not the desired one. If I can't pass a single sequence as the argument, how can I/should I break up the sequence into multiple arguments? Thanks.
(use '[clojure.contrib.combinatorics :only (cartesian-product)])
(cartesian-product (["a" "b" "c"] [1 2 3]))
Results in:
((["a" "b"]) ([1 2]))
Desired result
(("a" 1) ("a" 2) ("b" 1) ("b" 2))
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
Passing two lists and 'sum' function to map() Define a function sum, which returns sum of two numbers. Declaring and initializing lst1 and lst2. Passing sum function, list1 and list2 to map(). The element at index 0 from both the list will pass on as argument to sum function and their sum will be returned.
In Python, we can define two types of parameters that have variable lengths. They can be considered special types of optional parameters. In other words, there is no limit to the number of arguments that are passed to the parameter when we call this function.
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
the apply
function builds a function call from a function and a sequence containing the arguments to the function.
(apply cartesian-product '(["a" "b" "c"] [1 2 3]))
(("a" 1) ("a" 2) ("a" 3) ("b" 1) ("b" 2) ("b" 3) ("c" 1) ("c" 2) ("c" 3))
as another example:
(apply + (range 10))
evaluates (range 10)
into a sequence (0 1 2 3 4 5 6 7 8 9)
and then builds this function call
(+ 0 1 2 3 4 5 6 7 8 9)
fortunatly the for function does this nicely.
(for [x ["a" "b"] y [1 2]] [x y])
(["a" 1] ["a" 2] ["b" 1] ["b" 2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With