When working in the interpreter, it's often convenient to bind a function to a name, for example:
ghci> let f = (+1)
ghci> f 1
2
This aliases the name f
to the function (+1)
. Simple.
However, this doesn't always work. One example I've found which causes an error is trying to alias nub
from the Data.List
module. For example,
ghci> :m Data.List
ghci> nub [1,2,2,3,3,3]
[1,2,3]
ghci> let f = nub
ghci> f [1,2,2,3,3,3]
<interactive>:1:14:
No instance for (Num ())
arising from the literal `3'
Possible fix: add an instance declaration for (Num ())
In the expression: 3
In the first argument of `f', namely `[1, 2, 2, 3, ....]'
In the expression: f [1, 2, 2, 3, ....]
However, if I explicitly state the argument x
then it works without error:
ghci> let f x = nub x
ghci> f [1,2,2,3,3,3]
[1,2,3]
Can anyone explain this behaviour?
The bind() method creates a new function where this keyword refers to the parameter in the parenthesis in the above case geeks. This way the bind() method enables calling a function with a specified this value. Example 4: In this example there is 3 objects, and each time we call each object by using bind()method.
You can use call() / apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.
bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
The call() and apply() are very similar methods. They both execute the bound function on the object immediately. The bind() method does not execute the function right away. Instead, it creates and returns a bound function that can be executed later.
Type defaulting rules in current Ghci versions are somewhat inscrutable.
You can supply a type signature for f
. Or add :set -XNoMonomorphismRestriction
to your ~/.ghci
file as was advised by Chris earlier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With