Why does my CoffeeScript program issue 'number is not a function' error? - coffeescript

In the program below the first two logs work fine. I'm not doing anything new in the third and final log but somehow it crashes at runtime. Where is the error in my script? I have looked it over a large number of times and it seems like a fairly trivial modification of the proven working code above it.
sumSq = (n) -> ([0..n].map (i) -> i * i).reduce (a, b) -> a + b
sq = (n) -> n * n
sqSum = ((n) -> ([0..n].reduce (a, b) -> a + b))
console.log(sqSum 5)
console.log(sq(sqSum 5))
newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b))
console.log(newSqSum(5))

This is a function, not a number:
(n) -> ([0..n].reduce (a, b) -> a + b)
so when you say this:
newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b))
you're calling sq with a function as its argument. Then sq will try to multiply that function with itself and the result will be NaN because there is no sensible numeric representation of a function. And finally, your third console.log tries to call that NaN value as function and there's your error message.
Something of the form fn1 fn2, for functions f1 and f2, is not a function composition, it is in fact the same as writing fn1(fn2) and that won't produce a new function unless fn1 is explicitly constructed to return a function. If you want to compose the functions then I think you need to do it by hand:
newSqSum = (n) -> sq ((n) -> ([0..n].reduce (a, b) -> a + b)) n
# Or with less hate for the people maintaining your code:
newSqSum = (n) -> sq sqSum n

Related

Arrows' pronunciation

I'm not an English native speaker, so I'm wondering how to read out the related code, like:
(a -> A, b-> B) how to read this? "a right arrows A, b right arrows B"?
for( a <- list) this? "a left arrow list", or just "for a in the list"?
case _ => a this? hmmm...
I can understand the function but can only describe the meaning instead of the specific arrows. Shall I just speak out as "for a in the list"? I think that might be not so clear to the other listeners sometimes.
How to communicate with others in English for these arrow characters?
Perhaps a general notion of map as a synonym for a function
a -> A map a to A
b -> B map a to B
(a -> A, b-> B) map tuple (a -> B) to tuple (b -> B)
for (a <- list) yield a + 1 map a in list to a + 1
case _ => a map anything to a
or phrase "from _ to _"
a -> A from a to A
b -> B from b to B
(a -> A, b-> B) from tuple (a -> B) to tuple (b -> B)
for (a <- list) yield a + 1 from a in list to a + 1
case _ => a from anything to a
or phrase "if _ then _"
a -> A if a then A
b -> B if b then B
(a -> A, b-> B) if tuple (a -> B) then tuple (b -> B)
for (a <- list) yield a + 1 if a in list then a + 1
case _ => a if anything then a
There is a result claiming equivalence between the concept of function and implication, hence we can see the process of mapping as act of reasoning, so "if _ then _" might be fine.
As a side note, consider the difference between
for (...) yield (...) map every element
for (...) (...) execute side-effect for each element

Is there a function that transforms/maps both Either's Left and Right cases taking two transformation functions respectively?

I have not found a function in Scala or Haskell that can transform/map both Either's Left and Right cases taking two transformation functions at the same time, namely a function that is of the type
(A => C, B => D) => Either[C, D]
for Either[A, B] in Scala, or the type
(a -> c, b -> d) -> Either a b -> Either c d
in Haskell. In Scala, it would be equivalent to calling fold like this:
def mapLeftOrRight[A, B, C, D](e: Either[A, B], fa: A => C, fb: B => D): Either[C, D] =
e.fold(a => Left(fa(a)), b => Right(fb(b)))
Or in Haskell, it would be equivalent to calling either like this:
mapLeftOrRight :: (a -> c) -> (b -> d) -> Either a b -> Either c d
mapLeftOrRight fa fb = either (Left . fa) (Right . fb)
Does a function like this exist in the library? If not, I think something like this is quite practical, why do the language designers choose not to put it there?
Don't know about Scala, but Haskell has a search engine for type signatures. It doesn't give results for the one you wrote, but that's just because you take a tuple argument while Haskell functions are by convention curried†. https://hoogle.haskell.org/?hoogle=(a -> c) -> (b -> d) -> Either a b -> Either c d does give matches, the most obvious being:
mapBoth :: (a -> c) -> (b -> d) -> Either a b -> Either c d
...actually, even Google finds that, because the type variables happen to be exactly as you thought. (Hoogle also finds it if you write it (x -> y) -> (p -> q) -> Either x p -> Either y q.)
But actually, as Martijn said, this behaviour for Either is only a special case of a bifunctor, and indeed Hoogle also gives you the more general form, which is defined in the base library:
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d
†TBH I'm a bit disappointed that Hoogle doesn't by itself figure out to curry the signature or to swap arguments. Pretty sure it actually used to do that automatically, but at some point they simplified the algorithm because with the huge number of libraries the time it took and number of results got out of hand.
Cats provides Bifunctor, for example
import cats.implicits._
val e: Either[String, Int] = Right(41)
e.bimap(e => s"boom: $e", v => 1 + v)
// res0: Either[String,Int] = Right(42)
The behaviour you are talking about is a bifunctor behaviour, and would commonly be called bimap. In Haskell, a bifunctor for either is available: https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html
Apart from the fold you show, another implementation in scala would be either.map(fb).left.map(fa)
There isn't such a method in the scala stdlib, probably because it wasn't found useful or fundamental enough. I can somewhat relate to that: mapping both sides in one operation instead of mapping each side individually doesn't come across as fundamental or useful enough to warrant inclusion in the scala stdlib to me either. The bifunctor is available in Cats though.
In Haskell, the method exists on Either as mapBoth and BiFunctor is in base.
In Haskell, you can use Control.Arrow.(+++), which works on any ArrowChoice:
(+++) :: (ArrowChoice arr) => arr a b -> arr c d -> arr (Either a c) (Either b d)
infixr 2 +++
Specialised to the function arrow arr ~ (->), that is:
(+++) :: (a -> b) -> (c -> d) -> Either a c -> Either b d
Hoogle won’t find +++ if you search for the type specialised to functions, but you can find generalised operators like this by replacing -> in the signature you want with a type variable: x a c -> x b d -> x (Either a b) (Either c d).
An example of usage:
renderResults
:: FilePath
-> Int
-> Int
-> [Either String Int]
-> [Either String String]
renderResults file line column
= fmap ((prefix ++) +++ show)
where
prefix = concat [file, ":", show line, ":", show column, ": error: "]
renderResults "test" 12 34 [Right 1, Left "beans", Right 2, Left "bears"]
==
[ Right "1"
, Left "test:12:34: error: beans"
, Right "2"
, Left "test:12:34: error: bears"
]
There is also the related operator Control.Arrow.(|||) which does not tag the result with Either:
(|||) :: arr a c -> a b c -> arr (Either a b) c
infixr 2 |||
Specialised to (->):
(|||) :: (a -> c) -> (b -> c) -> Either a b -> c
Example:
assertRights :: [Either String a] -> [a]
assertRights = fmap (error ||| id)
sum $ assertRights [Right 1, Right 2]
==
3
sum $ assertRights [Right 1, Left "oh no"]
==
error "oh no"
(|||) is a generalisation of the either function in the Haskell Prelude for matching on Eithers. It’s used in the desugaring of if and case in arrow proc notation.

COQ definition curry howard (A -> B -> C) -> (B -> A -> C) using sets

I've been staring this in the face for hours not understanding :(
I need to solve some definitions using coq, and I am supposed to do it via the Curry Howard isomorphism. I have read up and still have no clue what I am doing. I have looked at other examples and tried doing it those ways and I always get errors.
For example, here I need to define this:
Variables A B C : Set.
Definition c01 : (A -> B -> C) -> (B -> A -> C) :=
this was my attempt:
fun g => fun p => g (snd p) (fst p).
end.
I also tried
fun f => fun b => fun a => f (b , a)
end.
Eventually it just says it was expecting a different type than what I gave, and sometimes it says things like: "expected to have type "?9 * ?10"."
Really struggling to grasp this after reading everything I could find.
Please could somebody explain :(
Well I guess you do not know how to read the types correctly.
c01's type is (A -> B -> C) -> (B -> A -> C). That means it is a function, which takes a function as argument and returns a function.
It takes "a function with two arguments" (I mean in the Haskell sense of "a function with two arguments", not in the Scala or Java sense), of type A and B, which returns a value of type C.
It must return a function with two arguments, of type A and B (but in the other order), which returns a value of type C.
So what must this function, c01, do?
It must take a function, and turn it into the same function with the order of its arguments reversed.
So:
fun f => fun b => fun a => f a b
Or equivalently (just adding some parentheses to make it clearer):
fun f => (fun b => fun a => f a b)

Anorm is just locking on executeUpdate

I have a very simple Play 2.1 Scala project. As in, this is the only code in it so far. I have a task which I am running with an Akka.system.scheduler. I have some code to select from the database (currently the standard test H2 instance) and I'm following the documentation example almost exactly.
DB.withConnection { implicit c =>
Logger.info("2")
var x = SQL("insert into x (a, b, c) values ({a, b, c})").on(
'a -> a,
'b -> b,
'c -> c
)
Logger.info("2.5")
x.executeUpdate()
Logger.info("3")
It never gets past 2.5. I haven't got any other database operations happening (except for evolutions).
Help?
Based on your link, shouldn't your SQL statement look like:
var x = SQL("insert into x (a, b, c) values ({a}, {b}, {c})").on(
"a" -> a,
"b" -> b,
"c" -> c
)
In the question the values don't have individual braces: {a, b, c}.

composition of the functions

I need to write some function NTimesComposition(f:(int * int -> int), n:int) which receives some function f and integer n and after doing composition of f, n times, like this f(x,(f(x,f(x,y)))) <- (here for example n = 3) I began to write it on smlnj, but it seems more complicated than I thought thanks in advance for any idea:
NTimesComposition(f:(int * int -> int), n:int)
if n = 1 then fn(x,y) => f(x, y ) else NTimesComposition...//here I'm stuck, must be recurstion
You already got it for n = 1 and you most likely just forgot to pass the (x, y) in the recursive call for n > 1. Obviously here it needs to be something of the form fn (x,y) => f (x, ...) where the ... part is where your recursive calls is going to be.
If you had forgot the (x,y) in the recursive part making it fn (x,y) => NTimesComposition (f, n-1) then you would end up building a chain of anonymous functions as "long" as your argument n describes. That would result in a different type of your NTimesComposition function depending on what n you supply which is not valid due to the way SML's type system works (Hindley-Milner).
The following two functions will do the job for you
fun foo (f, 1) = (fn xy => f xy)
| foo (f, n) = (fn (x,y) => f(x, foo (f, n-1) (x,y)))
and
fun baz (f, 1) xy = f xy
| baz (f, n) (x,y) = f(x, foo (f, n-1) (x,y))
where the first resembles your code the most using the anonymous function.