In Common Lisp you can do this:
(defun foo (bar &key baz quux)
(list bar baz quux))
(foo 1 :quux 3 :baz 2) ; => (1 2 3)
Clojure doesn't have keyword arguments. One alternative is this:
(defn foo [bar {:keys [baz quux]}]
(list bar baz quux))
(foo 1 {:quux 3 :baz 2}) ; => (1 2 3)
That's too many nested brackets to have to type and read all the time. It also requires an explicit hash-map to be passed in as an argument rather than a flat list.
What's the most idiomatic Clojure equivalent of keyword arguments that doesn't look someone set off a punctuation bomb?
To update this answer for Clojure 1.2 there is now full keyword arg support with defaults provided by the map forms of destructuring binding:
user> (defn foo [bar &{ :keys [baz quux]
:or {baz "baz_default" quux "quux_default"}}]
(list bar baz quux))
#'user/foo
user> (foo 1 :quux 3)
(1 "baz_default" 3)
A simple way to simulate keyword args in clojure is using hash-map on rest parameters like this:
> (defn kwtest [x & e] (:foo (apply hash-map e)))
#'user/kwtest
> (kwtest 12 :bar "ignored" :foo "returned")
"returned"
Rich Hickey provided a macro in this message from the clojure google group that gives you keyword parameters. The corresponding thread contains information about why keyword parameters are not supported by clojure. Basically to avoid the runtime overhead. Rich explains the method I've shown above in this message
A recent addition to clojure.contrib.def is the defnk macro, which enables definition of functions with keyword arguments (see here).
Related
So I was quite impressed the other day when I saw...
type Foo<'a> =
abstract foo : Unit -> 'a
type IsFoo<'a,'b when 'a :> Foo<'b>> = 'a
(I know this example is a bit daft)
the point being that complex parametric constraints can be captured in a type alias....nice
I then started using this a bit, but I got to a point where I have a function that requires a Bar
type Bar<'b> =
abstract bar : Unit -> 'b
and so we have
type IsBar<'a,'b when 'a :> Bar<'b>> = 'a
but then I wanted a Foo that returned a Bar....so I COULD go....(I think)
type IsFooThenBar<'a,'b,'c when 'a :> Foo<'b> and 'b :> Bar<'c>> =
IsFoo<'a,IsBar<'b,'c>>
but this is sort of just a restatement of stuff I already know...really I'd quite like the constraint to be inferred i.e.
type IsFooThenBar2<'a,'b,'c> = IsFoo<'a,IsBar<'b,'c>>
but that clearly doesnt work because the compiler complains I cant assert IsFoo and IsBar unless I have the required contraints...
any ideas?....I have lots of generic constraints on my code, and these don't really play nicely with type declarations.
to clarify based on some feedback, how can I take a set of type aliases and compose them into more complex ones without simply restating them....i.e. I want to be able to ammend one of the axiomatic aliases, and that be reflectied into derived aliases, without lots and lots and lots of typing.
so making this concrete, I can write
let f (x : IsFoo<_,IsBar<_,string>>) =
x.foo().bar()
which in simple cases is OK...but remember I have lots and lots of parameters...
so I really want to simplify this and write...
let f2 (x : IsFooThenBar<_,_,string>) =
x.foo().bar()
and I can of course do that if I define IsFooThenBar as described above....
i.e. type aliases give me the mechanism I want, but there seems to be no simple way to compose type aliases without restating all the constraints in the top level alias.
thats fine in this case....but for large numbers of parameters, it becomes more and more onerous.
So...an example of a language where you can do this sort of thing is Haskell...
> class Foo a b | a -> b where
> foo :: a -> b
>
> class Bar a b | a -> b where
> bar :: a -> b
> class (Foo foo bar,Bar bar a) => FooThenBar foo bar a where
I can then use FooThenBar as short hand for saying that there exists functions that map a 'foo to a 'bar and a 'bar to whatever type I specify
(I'm not Haskell expert and had to get help to create this loosely equivalent scenario)
this is the original function
> f :: (Bar bar b, Foo foo bar) => foo -> b
> f x = bar (foo x)
and this uses the new inferred composition
> f' :: (FooThenBar foo bar b) => foo -> b
> f' x = bar (foo x)
I was asked what's the relationship between partial function application and closures.
I would say there isn't any, unless I'm missing the point.
Let's say I'm writing in python and I have a very simple function MySum defined as follows:
MySum = lambda x, y : x + y;
Now I'm fixing one parameter to obtain a function with smaller arity which returns the same value that MySum would return if I called it with the same parameters (partial application):
MyPartialSum = lambda x : MySum(x, 0);
I could do the the very same thing with C:
int MySum(int x, int y) { return x + y; }
int MyPartialSum(int x) { return MySum(x, 0); }
So, the dumb question is: what's the difference? Why should I need closures for partial applications? These codes are equivalent, I don't see what's the bound with closures and partial application.
Partial function application is about fixing some arguments of a given function to yield another function with fewer arguments, like
sum = lambda x, y: x + y
inc = lambda x: sum(x, 1)
Notice that 'inc' is 'sum' partially applied, without capturing anything from the context (as you mentioned closure).
But, such hand-written (usually anonymous) functions are kind of tedious. One can use a function factory, which returns an inner function. The inner function can be parameterized by capturing some variable from its context, like
# sum = lambda x, y: x + y
def makePartialSumF(n):
def partialSumF(x):
return sum(x, n)
return partialSumF
inc = makePartialSumF(1)
plusTwo = makePartialSumF(2)
Here the factory makePartialSumF is invoked twice. Each call results in a partialSumF function (capturing different values as n). Using closure makes the implementation of partial application convenient. So you can say partial application can be implemented by means of closure. Of course, closures can do many other things! (As a side node, python does not have proper closure.)
Currying is about turning a function of N arguments into a unary function which returns a unary function... for example we have a function which takes three arguments and returns a value:
sum = lambda x, y, z: x + y + z
The curried version is
curriedSum = lambda x: lambda y: lambda z: x + y + z
I bet you wouldn't write python code like that. IMO the motivation of Currying is mostly of theoretical interest. (A framework of expressing computations using only unary functions: every function is unary!) The practical byproduct is that, in languages where functions are curried, some partial applications (when you 'fix' arguments from the left) are as trivial as supplying arguments to curried function. (But not all partial applications are as such. Example: given f(x,y,z) = x+2*y+3*z, when you binds y to a constant to yield a function of two variables.) So you can say, Currying is a technique which, in practice and as a byproduct, can make many useful partial functional applications trivial, but that's not the point of Currying.
Partial application is a technique whereby you take an existing function and a subset of it's arguments, and produce a new function that accepts the remaining arguments.
In other words, if you have function F(a, b), a function that applies partial application of a would look like B(fn, a) where F(a, b) = B(F, a)(b).
In your example you're simply creating new functions, rather than applying partial application to the existing one.
Here's an example in python:
def curry_first(fn, arg):
def foo(*args):
return fn(arg, *args)
return foo
This creates a closure over the supplied function and argument. A new function is returned that calls the first function with new argument signature. The closure is important - it allows fn access to arg. Now you can do this sort of thing:
add = lambda x, y : x + y;
add2 = curry_first(add, 2)
add2(4) # returns 6
I've usually heard this referred to as currying.
Simply, the result of a partial application is normally implemented as a closure.
Closures are not a required functionality in a language. I'm experimenting a homemade language, lambdatalk, in which lambdas don't create closures but accept partial application. For instance this is how the set [cons, car, cdr] could be defined in SCHEME:
(def cons (lambda (x y) (lambda (m) (m x y))))
(def car (lambda (z) (z (lambda (p q) p))))
(def cdr (lambda (z) (z (lambda (p q) q))))
(car (cons 12 34)) -> 12
(cdr (cons 12 34)) -> 34
and in lambdatalk:
{def cons {lambda {:x :y :m} {:m :x :y}}}
{def car {lambda {:z} {:z {lambda {:x :y} :x}}}}
{def cdr {lambda {:z} {:z {lambda {:x :y} :y}}}}
{car {cons 12 34}} -> 12
{cdr {cons 12 34}} -> 34
In SCHEME the outer lambda saves x and y in a closure the inner lambda can access given m. In lambdatalk the lambda saves :x and :y and returns a new lambda waiting for :m. So, even if closure (and lexical scope) are usefull functionalities, there are not a necessity. Without any free variables, out of any lexical scope, functions are true black boxes without any side effect, in a total independance, following a true functional paradigm. Don't you think so?
For me, using the partialSum that way, makes sure that you only depend on one Function to sum the numbers (MySum) and that will make debugging a lot more easier if things go wrong, because you would not have to worry about the logic of your code in two different parts of your code.
If in the future you decide to change the logic of MySum, (say for example, make it return x+y+1) then you will not have to worry about MyPartialSum because it calls MySum
Even if it seems stupid, having code written that way is just to simplify the process of dependencies in functions. I am sure you will notice that later in your studies.
Is the -> operator in Clojure (and what is this operator called in Clojure-speak?) equivalent to the pipeline operator |> in F#? If so, why does it need such a complex macro definition, when (|>) is just defined as
let inline (|>) x f = f x
Or if not, does F#'s pipeline operator exist in Clojure, or how would you define such an operator in Clojure?
No, they are not the same. Clojure doesn't really have a need for |> because all function calls are enclosed in lists, like (+ 1 2): there's no magic you could do to make 1 + 2 work in isolation.1
-> is for reducing nesting and simplifying common patterns. For example:
(-> x (assoc :name "ted") (dissoc :size) (keys))
Expands to
(keys (dissoc (assoc x :name "ted") :size))
The former is often easier to read, because conceptually you're performing a series of operations on x; the former code is "shaped" that way, while the latter needs some mental unraveling to work out.
1 You can write a macro that sorta makes this work. The idea is to wrap your macro around the entire source tree that you want to transform, and let it look for |> symbols; it can then transform the source into the shape you want. Hiredman has made it possible to write code in a very Haskell-looking way, with his functional package.
It's called the "thread" operator. It's written as a macro as opposed to a normal function for performance reasons and so that it can provide a nice syntax - i.e. it applies the transformation at compile time.
It's somewhat more powerful than the |> operator you describe, as it's intended to pass a value through several functions, where each successive value is "inserted" as the first parameter of the following function calls. Here's a somewhat contrived example:
(-> [1]
(concat [2 3 4])
(sum)
((fn [x] (+ x 100.0))))
=> 110.0
If you want to define a function exactly like the F# operator you have described, you can do:
(defn |> [x f] (f x))
(|> 3 inc)
=> 4
Not sure how useful that really is, but there you are anyway :-)
Finally, if you want to pass a value through a sequence of functions, you can always do something like the following in clojure:
(defn pipeline [x & fns]
((apply comp fns) x))
(pipeline 1 inc inc inc inc)
=> 5
It is also worth noting that there is a ->> macro which will thread the form as the last argument:
(->> a (+ 5) (let [a 5] ))
The Joy of Clojure, chapter 8.1 talks about this subject a bit.
When reading source code (especially when speaking), I always pronounce the -> operator as "thread-first", and the ->> operator as "thread-last".
Keep in mind that there is now an operator as-> which is more flexible than either -> or ->>. The form is:
(as-> val name (form1 arg1 name arg2)...)
The value val is evaluated and assigned to the placeholder symbol name, which the user can place in ANY position in the following forms. I usually choose the word "it" for the placeholder symbol. We can mimic thread-first -> like so:
user=> (-> :a
(vector 1))
[:a 1]
user=> (as-> :a it
(vector it 1) )
[:a 1]
We can mimic thread-last ->> like so:
user=> (->> :a
(vector 2))
[2 :a]
user=> (as-> :a it
(vector 2 it) )
[2 :a]
Or, we can combine them in a single expression:
user=> (as-> :a it
(vector it 1)
(vector 2 it))
[2 [:a 1]]
user=> (as-> :a it
(vector it 1)
(vector 2 it)
(vector "first" it "last"))
["first" [2 [:a 1]] "last"]
I use this last form so much I have made a new operator it-> in the Tupelo Library:
(it-> 1
(inc it) ; thread-first or thread-last
(+ it 3) ; thread-first
(/ 10 it) ; thread-last
(str "We need to order " it " items." ) ; middle of 3 arguments
;=> "We need to order 2 items." )
I am writing a lambda calculus in F#, but I am stuck on implementing the beta-reduction (substituting formal parameters with the actual parameters).
(lambda x.e)f
--> e[f/x]
example of usage:
(lambda n. n*2+3) 7
--> (n*2+3)[7/n]
--> 7*2+3
So I'd love to hear some suggestions in regards to how others might go about this. Any ideas would be greatly appreciated.
Thanks!
Assuming your representation of an expression looks like
type expression = App of expression * expression
| Lambda of ident * expression
(* ... *)
, you have a function subst (x:ident) (e1:expression) (e2:expression) : expression which replaces all free occurrences of x with e1 in e2, and you want normal order evaluation, your code should look something like this:
let rec eval exp =
match exp with
(* ... *)
| App (f, arg) -> match eval f with Lambda (x,e) -> eval (subst x arg e)
The subst function should work as follows:
For a function application it should call itself recursively on both subexpressions.
For lambdas it should call itself on the lambda's body expression unless the lambda's argument name is equal to the identifier you want to replace (in which case you can just leave the lambda be because the identifier can't appear freely anywhere inside it).
For a variable it should either return the variable unchanged or the replacement-expression depending on whether the variable's name is equal to the identifier.
I'd like to pre-store a bunch of function calls in a data structure and later evaluate/execute them from within another function.
This works as planned for functions defined at namespace level with defn (even though the function definition comes after my creation of the data structure) but will not work with functions defined by let [name (fn or letfn inside the function.
Here's my small self-contained example:
(def todoA '(funcA))
(def todoB '(funcB))
(def todoC '(funcC))
(def todoD '(funcD)) ; unused
(defn funcA [] (println "hello funcA!"))
(declare funcB funcC)
(defn runit []
(let [funcB (fn [] (println "hello funcB"))]
(letfn [(funcC [] (println "hello funcC!"))]
(funcA) ; OK
(eval todoA) ; OK
(funcB) ; OK
(eval todoB) ; "Unable to resolve symbol: funcB in this context" at line 2
(funcC) ; OK
(eval todoC) ; "Unable to resolve symbol: funcC in this context" at line 3
)))
In case you're wondering about my test setup, to see the result of those 6 statements I comment/uncomment specific of the OK/failing lines and then call (runit) from the REPL.
Is there a simple fix I could undertake to get eval'd quoted calls to functions to work for functions defined inside another function?
Update:
This (based on danlei's suggestion) does work. Let's see if I can get this method working in "real life!"
(def todoB '(funcB))
(declare funcB)
(defn runit []
(binding [funcB (fn [] (println "hello funcB"))]
(funcB)
(eval todoB) ; "Unable to resolve symbol: funcB in this context" at line 1!
))
Update:
This code is going into my solution for a Constraint Satisfaction Problem - I want to find out who owns the zebra! I'm fairly new to Clojure and especially functional programming, and this has made the exercise quite challenging. I'm falling into a lot of pits but I'm OK with that as it's part of the learning experience.
I used to specify the constraints as a bunch of simple vectors, like this:
[:con-eq :spain :dog]
[:abs-pos :norway 1]
[:con-eq :kools :yellow]
[:next-to :chesterfields :fox]
where the first of each vector would specify the kind of constraint. But that led me to an awkward implementation of a dispatch mechanism for those rules, so I decided to encode them as (quoted) function calls instead:
'(coloc :japan :parliament) ; 10
'(coloc :coffee :green) ; 12
'(next-to :chesterfield :fox) ; 5
so I can dispatch the constraining rule with a simple eval. This seems a lot more elegant and "lisp-y." However, each of these functions needs to access my domain data (named vars), and this data keeps changing as the program runs. I didn't want to blemish my rules by introducing an extra argument, so I wanted vars to be available to the eval'd functions via dynamic scoping.
I've now learned that dynamic scoping can be done using binding, but it also needs a declare.
Do you mean something like this?
(def foo '(bar))
(declare bar)
(binding [bar (fn [] (println "hello bar"))]
(eval foo))
If yes, your problem reduces to this:
(let [foo 1]
(eval 'foo))
This won't work, because eval does not evaluate in the lexical environment. You can get around that using vars:
(declare foo)
(binding [foo 1]
(eval 'foo))
As far as that is concerned, Clojure seems to have similar semantics to CL, cf. the CLHS:
Evaluates form in the current dynamic environment and the null lexical environment.
I think you're solving the wrong problem. In functional languages, functions are values and can be assigned to anything that can store any other value, e.g. a map. You shouldn't be trying to manipulate namespaces or evaling anything - this isn't perl.
Try something like this, and use assoc to change the map locally:
user=> (def fnmap {:funcA (fn [x] (inc x)), :funcB (fn [x] (* x 2))})
#'user/fnmap
user=> ((:funcA fnmap) 10)
11
user=> ((:funcB fnmap) 10)
20