Defining a function with "extra" parenthesis - clojure

Can anyone explain to me why
((fn ([x] x)) 1)
works and returns 1? (There's one "extra" set of parenthesis after the fn) Shouldn't it be the following?
((fn [x] x) 1)
Additionally,
((fn (([x] x))) 1)
(2 "extra" sets of parenthesis) fails with a "CompilerException System.ArgumentException: Parameter declaration([x] x) should be a vector". Why?
Thanks!

The extra set of parenthesis allows you to define a function taking a variable number of arguments. The following example defines a function that can take either one argument or two arguments:
(defn foo
([x] x)
([x y] (+ x y)))
You can see this as defining two functions under a single name. The appropriate function is going to be called depending on the number of argument you provide.
If you define a function with a fixed number of arguments, the two following forms are equivalent:
(defn bar ([x] x))
and
(defn baz [x] x)
With this in mind you can understand the compiler exception. You are trying to define a function as follows:
(defn qux
(([x] x)))
When using the extra set of parenthesis, closure expect the first element inside the parenthsesis to be a vector (within brackets). However in this case, the first element is ([x] x) which is a list and not a vector. This is the error you get.

Related

Cannot have first parameter as optional

Can you have a function with and optional parameter as the first and only parameter?
thus
(defn foo [& bar] (if (= bar) 1 2))
What & bar means at function definition is that all the rest of the arguments will be put into a list. It does not give any guarantees as to the size of the list, so it could be empty, with one or more items.
A better approach to having one and only optional argument, is to have it accept zero or one arguments:
(defn foo
([] (foo 12))
([bar] (if (= bar 12) 1 2)))
In this example, if you call the first function definition, with zero arity, it will simply call the second 1-arity function definition with a default value of 12.
This will work:
(defn foo [& bar]
(if (seq bar) 1 2))
Using seq is the way you are supposed to code 'not empty'. Not to be confused with seq?, which means something quite different, which will in fact return true here.
The important point is that bar becomes a list inside the function body. If you want to get this list back to what it was when you called the function then use apply, or deconstruct the list in the function itself, as being explained in the comments below...

Difference between Record constructor and positional factory function

Suppose I define a record called Node: (defrecord Node [tag attributes children]).
After this definition, according to the docstring of defrecord a factory function called ->Node is defined, as well as another factory function map->Node and a Java class constructor Node..
I'm wondering what exactly the difference is between the positional factory function ->Node and the constructor Node., apart from the normal differences between a Java class constructor / method on the one hand and a clojure function on the other (by normal differences I'm thinking things like the fact that functions are first-class in Clojure while methods are not).
(Update: see end of this answer for a note on primitive field types vs. parameter types of the ctor vs. parameter types of the factory.)
The positional factory just calls the constructor directly. The only interesting thing beyond that is that for records / types with large numbers of fields (namely over 20, which is the maximum number of positional arguments a Clojure function can accept) making the constructor call is slightly more involved (since you have to unpack some arguments from the rest-args seq); positional factories as emitted by defrecord and deftype handle that correctly, and moreover check that the correct number of arguments is supplied, throwing an appropriate exception if not.
This is documented in the docstring for the private function clojure.core/build-positional-factory; say (doc clojure.core/build-positional-factory) at the REPL to read it, or (source clojure.core/build-positional-factory) to see the source.
The end result looks roughly like this:
;; positional factory for a type with up to 20 fields
(defn ->Foo
"Construct a Foo."
[x y z]
(new Foo x y z))
;; positional factory for a type with many fields
(defn ->Bar
"Construct a Bar."
[a b c d e f g h i j k l m n o p q r s t & overage]
(if (= (count overage) 2)
(new Bar a b c d e f g h i j k l m n o p q r s t
(nth overage 0) (nth overage 1))
(throw
(clojure.lang.ArityException.
(+ 20 (count overage)) (name '->Bar))))))
A note on parameter types:
Not sure if this falls under the rubric of "normal differences", so I'll mention it explicitly: deftype / defrecord introduced classes may have fields of primitive types, in which case the corresponding parameters of the constructor will also be of primitive types. However, as of Clojure 1.5.1, the positional factories always take all-Object arguments, even if technically they could be declared as primitive-accepting functions (that is, if the primitive types involved are long and/or double and there are at most four positional parameters).
#{}, the empty set. Apart from the differences you've explicitly said you're not interested in, there are no other differences. ->Foo exists specifically because functions are more friendly than constructors.

SML: map function on list with a function that takes more than 1 argument

I have a list of N elements in SML.
I want to apply a function to every element in that list, so I use map.
However the function I want to apply has more than 1 argument like this:
foo a b (c, d)
Where a is the element I am using from the list and b c and d are predefined variables that are the same every time.
I declare my function like this:
fun foo2 = map foo aList b (c,d)
but I get an operator and operand error, which was expected but I can think of any other way to do this.
fun foo2 list = map (fn x => foo x b (c, d)) list
It would be most convenient if the order of foo's args were changed; you can, of course, make a wrapper:
fun foo_swapped_args b (c,d) a = foo a b (c, d)
Then you could do
map (foo_swapped_args b (c,d)) aList

Clojure Function Naming Conventions

Context
Suppose I have protocols ICursor, IFoo, IBar then I can have a function named:
(defn IFoo->IBar [foo] ... )
Now, suppose I have a function which takes two arguments
x: ICursor
y: IFoo
and output an object of type IBar.
Now, is there any standard way to denote this in a function name? For example, none of the following work:
(defn ICursor,IFoo->IBar [x y] ...)
because "," is treated as space
(defn (ICursor, IFoo)->IBar [x y] ... )
because () is treated as function application.
(defn [ICursor, IFoo]->IBar [x y] ... )
because [] is treated as vector.
Question
Is there a standard way to encode protocol types of arguments in the function name?
Thanks!
I don't think there is any such recommended way and it seems like sort of type annotations. There is one such project around giving type annotations to clojure code at this link.
You can use something like : (defn ICursor->IFoo->IBar [x y] ...) which denotes that the function takes ICursor and IFoo as params and return IBar, so basically last type is return type and before that everything is parameter type but I am not sure if that can be a long term or idiomatic solution because then where is the method actual name :) which is important then type annotation.

What is [] (list constructor) in Haskell?

I'm Having problems understanding functors, specifically what a concrete type is in LYAH. I believe this is because I don't understand what [] really is.
fmap :: (a -> b) -> f a -> f b
Is [], a type-constructor? Or, is it a value constructor?
What does it mean to have the type of: [] :: [a]?
Is it like Maybe type-constructor, or Just value constructor?
If it is like Just then how come Just has a signature like Just :: a -> Maybe a rather than Just :: Maybe a, in other words why isn't [] typed [] :: a -> [a]
LYAH says this as it applies to functors: Notice how we didn't write instance Functor [a] where, because from fmap :: (a -> b) -> f a -> f b, we see that the f has to be a type constructor that takes one type. [a] is already a concrete type (of a list with any type inside it), while [] is a type constructor that takes one type and can produce types such as [Int], [String] or even [[String]]. I'm confused though the type of [] implies it is like a literal for [a] what is LYAH trying to get at?
The type is described (in a GHCI session) as:
$ ghci
Prelude> :info []
data [] a = [] | a : [a] -- Defined
We may also think about it as though it were defined as:
data List a = Nil
| Cons a (List a)
or
data List a = EmptyList
| ListElement a (List a)
Type Constructor
[a] is a polymorphic data type, which may also be written [] a as above. This may be thought about as though it were List a
In this case, [] is a type constructor taking one type argument a and returning the type [] a, which is also permitted to be written as [a].
One may write the type of a function like:
sum :: (Num a) => [a] -> a
Data Constructor
[] is a data constructor which essentially means "empty list." This data constructor takes no value arguments.
There is another data constructor, :, which prepends an element to the front of another list. The signature for this data constructor is a : [a] - it takes an element and another list of elements and returns a resultant list of elements.
The [] notation may also be used as shorthand for constructing a list. Normally we would construct a list as:
myNums = 3 : 2 : 4 : 7 : 12 : 8 : []
which is interpreted as
myNums = 3 : (2 : (4 : (7 : (12 : (8 : [])))))
but Haskell permits us also to use the shorthand
myNums = [ 3, 2, 4, 7, 12, 8 ]
as an equivalent in meaning, but slightly nicer in appearance, notation.
Ambiguous Case
There is an ambiguous case that is commonly seen: [a]. Depending on the context, this notation can mean either "a list of a's" or "a list with exactly one element, namely a." The first meaning is the intended meaning when [a] appears within a type, while the second meaning is the intended meaning when [a] appears within a value.
It's (confusingly, I'll grant you) syntactically overloaded to be both a type constructor and a value constructor.
It means that (the value constructor) [] has the type that, for all types a, it is a list of a (which is written [a]). This is because there is an empty list at every type.
The value constructor [] isn't typed a -> [a] because the empty list has no elements, and therefore it doesn't need an a to make an empty list of a's. Compare to Nothing :: Maybe a instead.
LYAH is talking about the type constructor [] with kind * -> *, as opposed to the value constructor [] with type [a].
it is a type constructor (e.g. [Int] is a type), and a data constructor ([2] is a list structure).
The empty list is a list holding any type
[a] is like Maybe a, [2] is like Just 2.
[] is a zero-ary function (a constant) so it doesn't have function type.
Just to make things more explicit, this data type:
data List a = Cons a (List a)
| Nil
...has the same structure as the built-in list type, but without the (nicer, but potentially confusing) special syntax. Here's what some correspondences look like:
List = [], type constructors with kind * -> *
List a = [a], types with kind *
Nil = [], values with polymorphic types List a and [a] respectively
Cons = :, data constructors with types a -> List a -> List a and a -> [a] -> [a] respectively
Cons 5 Nil = [5] or 5:[], single element lists
f Nil = ... = f [] = ..., pattern matching empty lists
f (Cons x Nil) = ... = f [x] = ...`, pattern matching single-element lists
f (Cons x xs) = ... = f (x:xs) = ..., pattern matching non-empty lists
In fact, if you ask ghci about [], it tells you pretty much the same definition:
> :i []
data [] a = [] | a : [a] -- Defined in GHC.Types
But you can't write such a definition yourself because the list syntax and its "outfix" type constructor is a special case, defined in the language spec.