In a Codefights challenge where you have to add two numbers the user kaiochao had a super minimalisic answer
add = (+)
How does it work and has this functionality a own name?
Here's an explicit definition:
add a b = a + b
There is a feature in Haskell that says that we can rewrite a + b as (+) a b, this is due to the fact that operators are functions in Haskell. So we can rewrite:
add a b = (+) a b
But then we're doing nothing extra to the arguments of this function, so we can reduce this function by removing the explicit arguments*. Note that this requires an understanding of how function application in Haskell works:
add = (+)
This is because functions are data in Haskell. This is literally saying that plus and the function of addition are the same thing.
In practice, we can see this by substituting:
add 1 2
= (+) 1 2 -- Since add = (+), this can be read literally.
= 1 + 2 -- This is how operators work in Haskell.
= 3 -- Calculation.
This is known as pointfree style in Haskell.
*As #Benjamin Hodgson mentioned, this is called eta-reduction.
This “functionality” is just variable assignment. It works the same way as writing
three = 3
3 is just a Haskell value, which I can at any point give a new name, refer to it, and get something that's (at least, at runtime) indistinguishable from 3 itself.
The fact that add has a somewhat more complicated type, namely a function type, changes nothing about the way such variable assignments work. I can certainly define
root = sqrt
...and then evaluate root 4 to obtain 2.0 as the result. Or, for any custom function,
foo :: Int -> String
foo n = concat $ replicate n (show n)
bar = foo
GHCi> bar 3
"333"
GHCi> bar 7
"7777777"
All that is really no different from how I can also write
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import math
In [2]: root = math.sqrt
In [3]: root(4)
Out[3]: 2.0
What's a bit more interesting about add is that + is an infix operator (because it consists of non-letter characters). But Haskell allows using such infix operators pretty much just as liberally as any other variables, including that you can define your own. The only thing that's a bit different are the parsing rules. + can not be a standalone syntactic unit but has to be surrounded on each side with with arguments you want to add, or with parentheses. The latter, (+), is really what the plus operator is from the compiler's point of view: the binary function, not yet applied to any arguments. So, when you want to give this operator a new name, you need to write
add = (+)
Incidentally, you could also give it a new operator-name, like
(⊕) = (+)
...that could then be used like 3 ⊕ 4, just as you can with the standard + operator.
Related
As the title states, I see pieces of code online where the variables/functions have ' next to it, what does this do/mean?
ex:
function :: [a] -> [a]
function ...
function' :: ....
The notation comes from mathematics. It is read x prime. In pretty much any math manual you can find something like let x be a number and x' be the projection of ... (math stuff).
Why not using another convention? well, in mathematics It makes a lot of sense because It can be very pedagogical... In programming we aren't used to this convention so I don't see the point of using it, but I am not against it neither.
Just to give you an example of its use in mathematics so you can understand why It is used in Haskell. Below, the same triangle concept but one using prime convention and other not using it. It is pretty clear in the first picture that pairs (A, A'), (B, B'), ... are related by one being the vertex and the prime version being the midpoint of the oposite edge. Whereas in the second example, you just have to remember that A is the midpoint of the oposite edge of vertex P. First is easier and more pedagogical:
As the other answers said, function' is just another variable name. So,
don'tUse :: Int -> IO ()
don'tUse won'tBe''used'' = return ()
is just like
dontUse :: Int -> IO ()
dontUse wontBeUsed = return ()
with slightly different names. The only requirement is that the name starts with a lowercase-letter or underscore, after that you can have as many single-quote characters as you want.
Prelude> let _' = 1
Prelude> let _'' = 2
Prelude> let _''''''''' = 9
Prelude> _' + _'' * _'''''''''
19
...Of course it's not necessarily a good idea to name variables like that; normally such prime-names are used when making a slightly different version of an already named thing. For example, foldl and foldl' are functions with the same signature that do essentially the same thing, only with different strictness (which often affects performance memory usage and whether infinite inputs are allowed, but not the actual results).
That said, to the question
Haskell what does the ' symbol do?
– the ' symbol does in fact do various other things as well, but only when it appears not as a non-leading character in a name.
'a' is a character literal.
'Foo is a constructor used on the type level. See DataKinds.
'bar and ''Baz are quoted names. See TemplateHaskell.
I'm learning basic Haskell so I can configure Xmonad, and I ran into this code snippet:
newKeys x = myKeys x `M.union` keys def x
Now I understand what the M.union in backticks is and means. Here's how I'm interpreting it:
newKeys(x) = M.union(myKeys(x),???)
I don't know what to make of the keys def x. Is it like keys(def(x))? Or keys(def,x)? Or is def some sort of other keyword?
It's keys(def,x).
This is basic Haskell syntax for function application: first the function itself, then its arguments separated by spaces. For example:
f x y = x + y
z = f 5 6
-- z = 11
However, it is not clear what def is without larger context.
In response to your comment: no, def couldn't be a function that takes x as argument, and then the result of that is passed to keys. This is because function application is left-associative, which basically means that in any bunch of things separated by spaces, only the first one is the function being applied, and the rest are its arguments. In order to express keys(def(x)), one would have to write keys (def x).
If you want to be super technical, then the right way to think about it is that all functions have exactly one parameter. When we declare a function of two parameters, e.g. f x y = x + y, what we really mean is that it's a function of one parameter, which returns another function, to which we can then pass the remaining parameter. In other words, f 5 6 means (f 5) 6.
This idea is kind of one of the core things in Haskell (and any ML offshoot) syntax. It's so important that it has its own name - "currying" (after Haskell Curry, the mathematician).
I've come across a piece of Haskell code that looks like this:
ps#(p:pt)
What does the # symbol mean in this context? I can't seem to find any info on Google (it's unfortunately hard to search for symbols on Google), and I can't find the function in the Prelude documentation, so I imagine it must be some sort of syntactic sugar instead.
Yes, it's just syntactic sugar, with # read aloud as "as". ps#(p:pt) gives you names for
the list: ps
the list's head : p
the list's tail: pt
Without the #, you'd have to choose between (1) or (2):(3).
This syntax actually works for any constructor; if you have data Tree a = Tree a [Tree a], then t#(Tree _ kids) gives you access to both the tree and its children.
The # Symbol is used to both give a name to a parameter and match that parameter against a pattern that follows the #. It's not specific to lists and can also be used with other data structures.
This is useful if you want to "decompose" a parameter into it's parts while still needing the parameter as a whole somewhere in your function. One example where this is the case is the tails function from the standard library:
tails :: [a] -> [[a]]
tails [] = [[]]
tails xxs#(_:xs) = xxs : tails xs
I want to add that # works at all levels, meaning you can do this:
let a#(b#(Just c), Just d) = (Just 1, Just 2) in (a, b, c, d)
Which will then produce this: ((Just 1, Just 2), Just 1, 1, 2)
So basically it's a way for you to bind a pattern to a value. This also means that it works with any kind of pattern, not just lists, as demonstrated above. This is a very useful thing to know, as it means you can use it in many more cases.
In this case, a is the entire Maybe Tuple, b is just the first Just in the tuple, and c and d are the values contained in the first and second Just in the tuple respectively
To add to what the other people have said, they are called as-patterns (in ML the syntax uses the keyword "as"), and are described in the section of the Haskell Report on patterns.
I just started Haskell and I'm struggling!!!
So I need to create a list om Haskell that has the formula
F(n) = (F(n-1)+F(n-2)) * F(n-3)/F(n-4)
and I have F(0) =1, F(1)=1,F(2)=1,F(3)=1
So I thought of initializing the first 4 elements of the list and then have a create a recursive function that runs for n>4 and appends the values to the list.
My code looks like this
let F=[1,1,1,1]
fib' n F
| n<4="less than 4"
|otherwise = (F(n-1)+F(n-2))*F(n-3)/F(n-4) : fib (n-1) F
My code looks conceptually right to me(not sure though), but I get an incorrect indentation error when i compile it. And am I allowed to initialize the elements of the list in the way that I have?
First off, variables in Haskell have to be lower case. Secondly, Haskell doesn't let you mix integers and fractions so freely as you may be used to from untyped or barely-typed languages. If you want to convert from an Int or an Integer to, say, a Double, you'll need to use fromIntegral. Thirdly, you can't stick a string in a context where you need a number. Fourthly, you may or may not have an indentation problem—be sure not to use tabs in your Haskell files, and to use the GHC option -fwarn-tabs to be sure.
Now we get to the heart of the matter: you're going about this all somewhat wrong. I'm going to give you a hint instead of a full answer:
thesequence = 1 : 1 : 1 : 1 : -- Something goes here that *uses* thesequence
Let's say I have a function which can calculate power of four of a number defined by
let power4 x = x*x*x*x
And I try to pass x = (3 + 8)*2
let result = power4 ((3 + 8)*2)
Since in Haskell, the values are evaluated until they are needed, does it mean that x will evaluate four times? If so, is there any way to improve the Haskell compiler?
Thanks.
No, it will only be evaluated once. In call by name it would be evaluated four times, but all Haskell implementations are call by need (although the standard does not require this), which means each expression will be evaluated at most once.
This only applies when the expression is fully concrete. E.g. there is no guarantee that in:
foo x = x + (1+2)
bar = foo 3 + foo 4
That when computing bar, (1+2) will be evaluated only once. In fact, it will probably be evaluated twice (if compiled without optimizations).
If you aren't sure, you could use trace to check (ref: http://www.haskell.org/haskellwiki/Debugging):
import Debug.Trace
power4 x = x*x*x*x
main = print $ power4 (trace "called" ((3+8)*2))
result:
called
234256
so the expression is only evaluated once.