Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Sequence as Argument in Place of Multiple Arguments

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))
like image 943
Ari Avatar asked Oct 12 '11 19:10

Ari


People also ask

How to pass multiple arguments in a function?

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.

How to pass 2 arguments in map Python?

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.

How many arguments we can pass in Python?

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.

How can you get the type of arguments passed to a 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.


1 Answers

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)


and back by popular demand:

fortunatly the for function does this nicely.

(for [x ["a" "b"] y [1 2]] [x y])
(["a" 1] ["a" 2] ["b" 1] ["b" 2])
like image 155
Arthur Ulfeldt Avatar answered Nov 05 '22 14:11

Arthur Ulfeldt