i have this two functions and i use share-card-to-player in share-cards. Should i not rather pass share-card-to-player as argument or use it as anonymous function?
In the way, i am using it, i doubt, that i am using it in a functional way, because i am basically referencing to a global variable namely the function share-card-to-player. Is that assumption correct?
(defn share-card-to-player [game [player cards]]
(assoc-in game [:players player :cards ]
cards))
(defn share-cards [{players :players cards :cards :as game}]
(reduce share-card-to-player game
(map vector
(keys players)
(->> cards
(partition (/ (count cards)
(count players)))))))
i am basically referencing to a global variable namely the function share-card-to-player
assoc-in is a global variable. / is a global variable. count is a global variable. Should you avoid them all? It will be tough to get anything done! The problem with globals is mutation, and functions are not mutable.
You can define share-card-to-player as an anonymous local function if you want. But it's fine as is. Extracting it as a function parameter would make sense only if you expect you would want to pass another function to it at another use site.
Passing in the function as a parameter would only make sense to me if you plan to pass in different functions in other parts of your program to change the behavior of share-cards.
In your particular example, I'd even consider factoring out the call to map if you can give a good name to that thing because it takes longer to read and understand that code.
To summarize:
Functions as parameter should change the behavior.
Factoring out things to their own functions, even if only used in one place of your program, makes sense if you can give a good name to what the code does.
Related
When developing with Common Lisp, we have three possibilities to define new setf-forms:
We can define a function whose name is a list of two symbols, the first one being setf, e.g. (defun (setf some-observable) (…)).
We can use the short form of defsetf.
We can use the long form of defsetf.
We can use define-setf-expander.
I am not sure what is the right or intended use-case for each of these possibilities.
A response to this question could hint at the most generic solution and outline contexts where other solutions are superior.
define-setf-expander is the most general of these. All of setf's functionality is encompassed by it.
Defining a setf function works fine for most accessors. It is also valid to use a generic function, so polymorphism is insufficient to require using something else. Controlling evaluation either for correctness or performance is the main reason to not use a setf function.
For correctness, many forms of destructuring are not possible to do with a setf function (e.g. (setf (values ...) ...)). Similarly I've seen an example that makes functional data structures behave locally like a mutable one by changing (setf (dict-get key some-dict) 2) to assign a new dictionary to some-dict.
For performance, consider the silly case of (incf (nth 10000 list)) which if the nth writer were implemented as a function would require traversing 10k list nodes twice, but in a setf expander can be done with a single traversal.
I am teaching myself Common Lisp. I have been looking at an example of Conway's game of life, and there is a piece of syntax I do not understand.
The complete code is available here. The part in particular I am having trouble with is as follows:
(defstruct (world (:constructor %make-world))
current
next)
(defun make-world (width height)
(flet ((make-plane (width height)
(make-array (list width height)
:element-type 'bit
:initial-element 0)))
(%make-world
:current (make-plane width height)
:next (make-plane width height))))
I am wondering, first, what is the significance of the percent-sign in %make-world? Second, why does the constructor specify two different names? (make-world and %make-world) I have seen this syntax in use before, but the names are always the same. It seems like there is some deeper functionality, but it is escaping me.
There are several naming conventions is the Lisp world when it comes to identifiers. For an overview see: http://www.cliki.net/Naming+conventions
Making objects or structures can be done with system generated functions. DEFSTRUCT will create a MAKE-FOO function with init values for the slots as keyword arguments.
Sometimes people prefer functions with normal positional arguments - it's shorter to write and the arguments have to be given when calling the function - you can't omit them.
Here in this case there is the need to name the DEFSTRUCT generated function in such a way that it does not collide with the name, which the user should use. So %MAKE-FOO says that is an internal helper function to the library and is expected to NOT be called by user-level code.
My Lisp is a little rusty, but I believe it goes like this:
The % sign has no special meaning. I've seen it used for internal functions (e.g. defined by labels), but nothing wil stop you from calling it normally. If you look at defstruct documetation, you'll see that (:constructor %make-world) defines a named constructor %make-world (by default the constructor would be called make-world. This contructor can be used to create world structs, initializing fields using named parameters.
The function make-world exists to make creating these structs easier. The thing is, current and next should be 2-dimensional arrays, but it's more convenient if, instead of passing these arrays to the constructor, you could just say what the dimensions are and a function would create those arrays for you. Which is exactly what make-world does here. It first defines an internal function make-plane, which can create an array, then uses it to create 2 arrays and pass them to the constructor %make-plane.
In line with the usual usage of the % character (again, this is just a convention), it tells you that, as a programmer wishing to use the world struct, you should not use the %make-world constructor, but the make-world function instead.
Is there a better way to do this in Clojure?
(if (coll? coll)
(map my-fn coll)
(my-fn coll)
my-fn is to be applied to input coll. coll can be either singular or a collection.
If I don't check for coll?, using map alone would throw an IllegalArgumentException for don't know how to create an ISeq from xxx.
Your code is fine (although I'd rename the variable coll since you don't actually know if it is a collection and this might confuse readers).
However I'd suggest this whole chunk of code looks suspiciously like a code smell - it's taking dynamic typing a bit too far / trying to be a bit too clever in my opinion: in the sense of "cleverness considered harmful".
Alternative ideas to consider:
If you actually want to treat everything like a collection, then wrap singular input values when they are first obtained in a list/vector of length 1. Then the rest of your code can safely assume collections throughout.
Write separate functions to deal with collections and single values. The rationale is that they are conceptually different data types, so deserve different treatment.
If coll doesn't contain any nested sequences:
(map my-fn (flatten (list coll)))
No general solution can exist, because my-fn may be a function that takes lists and returns lists. Then you can't somehow inspect the input and decide whether to map over it or not.
Better is to not get yourself into the scenario where you don't know what type of data you have, but I can't give any specific advice on this without knowing more about your program.
I'm learning functional programming, and have tried to solve a couple problems in a functional style. One thing I experienced, while dividing up my problem into functions, was it seemed I had two options: use several disparate functions with similar parameter lists, or using nested functions which, as closures, can simply refer to bindings in the parent function.
Though I ended up going with the second approach, because it made function calls smaller and it seemed to "feel" better, from my reading it seems like I may be missing one of the main points of functional programming, in that this seems "side-effecty"? Now granted, these nested functions cannot modify the outer bindings, as the language I was using prevents that, but if you look at each individual inner function, you can't say "given the same parameters, this function will return the same results" because they do use the variables from the parent scope... am I right?
What is the desirable way to proceed?
Thanks!
Functional programming isn't all-or-nothing. If nesting the functions makes more sense, I'd go with that approach. However, If you really want the internal functions to be purely functional, explicitly pass all the needed parameters into them.
Here's a little example in Scheme:
(define (foo a)
(define (bar b)
(+ a b)) ; getting a from outer scope, not purely functional
(bar 3))
(define (foo a)
(define (bar a b)
(+ a b)) ; getting a from function parameters, purely functional
(bar a 3))
(define (bar a b) ; since this is purely functional, we can remove it from its
(+ a b)) ; environment and it still works
(define (foo a)
(bar a 3))
Personally, I'd go with the first approach, but either will work equally well.
Nesting functions is an excellent way to divide up the labor in many functions. It's not really "side-effecty"; if it helps, think of the captured variables as implicit parameters.
One example where nested functions are useful is to replace loops. The parameters to the nested function can act as induction variables which accumulate values. A simple example:
let factorial n =
let rec facHelper p n =
if n = 1 then p else facHelper (p*n) (n-1)
in
facHelper 1 n
In this case, it wouldn't really make sense to declare a function like facHelper globally, since users shouldn't have to worry about the p parameter.
Be aware, however, that it can be difficult to test nested functions individually, since they cannot be referred to outside of their parent.
Consider the following (contrived) Haskell snippet:
putLines :: [String] -> IO ()
putLines lines = putStr string
where string = concat lines
string is a locally bound named constant. But isn't it also a function taking no arguments that closes over lines and is therefore referentially intransparent? (In Haskell, constants and nullary functions are indeed indistinguishable!) Would you consider the above code “side-effecty” or non-functional because of this?
I was fooling around with some functional programming when I came across the need for this function, however I don't know what this sort of thing is called in standard nomenclature.
Anyone recognizes it?
function WhatAmIDoing(args...)
return function()
return args
end
end
Edit: generalized the function, it takes a variable amount of arguments ( or perhaps an implicit list) and returns a function that when invoked returns all the args, something like a curry or pickle, but it doesn't seem to be either.
WhatAmIDoing is a higher-order function because it is a function that returns another function.
The thing that it returns is a thunk — a closure created for delayed computation of the actual value. Usually thunks are created to lazily evaluate an expression (and possibly memoize it), but in other cases, a function is simply needed in place of a bare value, as in the case of "constantly 5", which in some languages returns a function that always returns 5.
The latter might apply in the example given, because assuming the language evaluates in applicative-order (i.e. evaluates arguments before calling a function), the function serves no other purpose than to turn the values into a function that returns them.
WhatAmIDoing is really an implementation of the "constantly" function I was describing. But in general, you don't have to return just args in the inner function. You could return "ackermann(args)", which could take a long time, as in...
function WhatAmIDoing2(args...)
return function()
return ackermann(args)
end
end
But WhatAmIDoing2 would return immediately because evaluation of the ackermann function would be suspended in a closure. (Yes, even in a call-by-value language.)
In functional programming a function that takes another function as an argument or returns another function is called a higher-order function.
I would say that XXXX returns a closure of the unnamed function bound on the values of x,y and z.
This wikipedia article may shed some light
Currying is about transforming a function to a chain of functions, each taking only one parameter and returning another such function. So, this example has no relation to currying.
Pickling is a term ususally used to denote some kind of serialization. Maybe for storing a object built from multiple values.
If the aspect interesting to you is that the returned function can access the arguments of the XXXX function, then I would go with Remo.D.
As others have said, it's a higher-order function. As you have "pattern" in your question, I thought I'd add that this feature of functional languages is often modelled using the strategy pattern in languages without higher-order functions.
Something very similar is called constantly in Clojure:
http://github.com/richhickey/clojure/blob/ab6fc90d56bfb3b969ed84058e1b3a4b30faa400/src/clj/clojure/core.clj#L1096
Only the function that constantly returns takes an arbitrary amount of arguments, making it more general (and flexible) than your pattern.
I don't know if this pattern has a name, but would use it in cases where normally functions are expected, but all I care for is that a certain value is returned:
(map (constantly 9) [1 2 3])
=> (9 9 9)
Just wondering, what do you use this for?
A delegate?
Basically you are returning a function?? or the output of a function?
Didn't understand, sorry...