Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can I bind a function to another name?

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?

like image 675
Chris Taylor Avatar asked Dec 28 '11 12:12

Chris Taylor


People also ask

When would you use the bind function?

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.

How do you call a function in bind?

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.

How does bind function work?

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.

What is common feature of call () apply () and bind ()?

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.


1 Answers

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.

like image 196
Mischa Arefiev Avatar answered Oct 06 '22 00:10

Mischa Arefiev