How to use 'aux' keyword in Haskell - haskell

Okay, I've looked on about 4-5 websites that offered to teach Haskell and not one of them explained the keyword aux. They just started using it. I've only really studied Java and C (never saw it in either if it exists), and I've never really encountered it before this class that I'm taking on Haskell. All I can really tell is that it provides the utility to create and store a value within a function. So what exactly does it do and how is it properly used and formatted? In particular, could you explain its use while recursing? I don't think that its use is any different, but just to make sure I thought I would ask.

There is no keyword aux, my guess is this is just the name they used for a local function.
Just like you can define top-level values:
myValue = 4
or top-level functions:
myFunction x = 2 * x
you can similarly define local values:
myValue =
let myLocalValue = 3 in
myLocalValue + 1
-- or equivalently:
myValue = myLocalValue + 1
where myLocalValue = 3
or a local function:
myValue =
let myLocalFunction x = 2 * x in
myLocalFunction 2
-- or equivalently:
myValue = myLocalFunction 2
where myLocalFunction x = 2 * x
Your teacher simply named the local function aux instead of myLocalFunction.

Related

Can I use where in Haskell to find function parameter given the function output?

This is my program:
modify :: Integer -> Integer
modify a = a + 100
x = x where modify(x) = 101
In ghci, this compiles successfully but when I try to print x the terminal gets stuck. Is it not possible to find input from function output in Haskell?
x = x where modify(x) = 101
is valid syntax but is equivalent to
x = x where f y = 101
where x = x is a recursive definition, which will get stuck in an infinite loop (or generate a <<loop>> exception), and f y = 101 is a definition of a local function, completely unrelated to the modify function defined elsewhere.
If you turn on warnings you should get a message saying "warning: the local definition of modify shadows the outer binding", pointing at the issue.
Further, there is no way to invert a function like you'd like to do. First, the function might not be injective. Second, even if it were such, there is no easy way to invert an arbitrary function. We could try all the possible inputs but that would be extremely inefficient.

Passing Variables in Function and compare each?

I'm trying to practice Haskell returns and datatypes. I'm trying to pass the following information into the program:
worm = 1:2:3:worm
eel = [1,2,3,1,2,3,1,2,3]
snake = 3:2:1:snake
whale = [1..100]
And i want to create a function that has a switch function to get the data and match it to its definition. For example, in Python:
def compare(str): #for one case and using string to clarify
if str == "1:2:3:worm":
return "worm"
I know the datatypes are lists but causes a lot of confusion. My code is giving me an error of Could not deduce (Num Char) Arising from use of worm
My code:
which :: [a] -> String
which x | x == [1,2,3,1,2,3,1,2,3] = "worm" | x == 3:2:1:snake = "snake" | otherwise = "F"
Is there another approach i'm missing? and why is my function giving me that error?
Two problems:
You can't have a function that returns a list of numbers sometimes and a string other times. That's literally the entire point of a strongly typed language. If you want something like that, you need to use a sum type.
You can't compare infinite lists. You can try, but your program will never finish.

What is this expression in Haskell, and how do I interpret it?

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).

GHCI Haskell not remembering bindings in command line

I am trying to learn Haskell but it is a little hard as non of my bindings are remembered from the command line; output from my terminal below.
> let b = []
> b
[]
> 1:b
[1]
> b
[]
I have no idea why this is like this can anyone please help.
What did you expect your example to do? From what you've presented, I don't see anything surprising.
Of course, that answer is probably surprising to you, or you wouldn't have asked. And I'll be honest: I can guess what you were expecting. If I'm right, you thought the output would be:
> let b = []
> b
[]
> 1:b
[1]
> b
[1]
Am I right? Supposing I am, then the question is: why isn't it?
Well, the short version is "that's not what (:) does". Instead, (:) creates a new list out of its arguments; x:xs is a new list whose first element is x and the rest of which is identical to xs. But it creates a new list. It's just like how + creates a new number that's the sum of its arguments: is the behavior
> let b = 0
> b
0
> 1+b
1
> b
0
surprising, too? (Hopefully not!)
Of course, this opens up the next question of "well, how do I update b, then?". And this is where Haskell shows its true colors: you don't. In Haskell, once a variable is bound to a value, that value will never change; it's as though all variables and all data types are const (in C-like languages or the latest Javascript standard) or val (in Scala).
This feature of Haskell – it's called being purely functional – is possibly the single biggest difference between Haskell and every single mainstream language out there. You have to think about writing programs in a very different way when you aren't working with mutable state everywhere.
For example, to go a bit further afield, it's quite possible the next thing you'll try will be something like this:
> let b = []
> b
[]
> let b = 1 : b
In that case, what do you think is going to be printed out when you type b?
Well, remember, variables don't change! So the answer is:
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,…
forever – or until you hit control-C and abort.
This is because let b = 1 : b defines a new variable named b; you might as well have written let c = 1 : c. Thus, you're saying "b is a list which is 1 followed by b"; since we know what b is, we can substitute and get "b is a list which is 1 followed by 1 followed by b", and so on forever. Or: b = 1 : b, so substituting in for b we get b = 1 : 1 : b, and substituting in we get b = 1 : 1 : 1 : 1 : ….
(The fact that Haskell produces an infinite list, rather than going into an infinite loop, is because Haskell is non-strict, more popularly referred to as lazy – this is also possibly the single biggest difference between Haskell and every single mainstream language out there. For further information, search for "lazy evaluation" on Google or Stack Overflow.)
So, in the end, I hope you can see why I wasn't surprised: Haskell can't possibly update variable bindings. So since your definition was let b = [], then of course the final result was still [] :-)

Are there any programming languages where variables are really functions?

For example, I would write:
x = 2
y = x + 4
print(y)
x = 5
print(y)
And it would output:
6 (=2+4)
9 (=5+4)
Also, are there any cases where this could actually be useful?
Clarification: Yes, lambdas etc. solve this problem (they were how I arrived at this idea); I was wondering if there were specific languages where this was the default: no function or lambda keywords required or needed.
Haskell will meet you halfway, because essentially everything is a function, but variables are only bound once (meaning you cannot reassign x in the same scope).
It's easy to consider y = x + 4 a variable assignment, but when you look at y = map (+4) [1..] (which means add 4 to every number in the infinite list from 1 upwards), what is y now? Is it an infinite list, or is it a function that returns an infinite list? (Hint: it's the second one.) In this case, treating variables as functions can be extremely beneficial, if not an absolute necessity, when taking advantage of laziness.
Really, in Haskell, your definition of y is a function accepting no arguments and returning x+4, where x is also a function that takes no arguments, but returns the value 2.
In any language with first order functions, it's trivial to assign anonymous functions to variables, but for most languages you'll have to add the parentheses to indicate a function call.
Example Lua code:
x = function() return 2 end
y = function() return x() + 4 end
print(y())
x = function() return 5 end
print(y())
$ lua x.lua
6
9
Or the same thing in Python (sticking with first-order functions, but we could have just used plain integers for x):
x = lambda: 2
y = lambda: x() + 4
print(y())
x = lambda: 5
print(y())
$ python x.py
6
9
you can use func expressions in C#
Func<int, int> y = (x) => x + 5;
Console.WriteLine(y(5)); // 10
Console.WriteLine(y(3)); // 8
... or ...
int x = 0;
Func<int> y = () => x + 5;
x = 5;
Console.WriteLine(y()); // 10
x = 3;
Console.WriteLine(y()); // 8
... if you are really wanting to program in a functional style the first option would probably be best.
it looks more like the stuff you saw in math class.
you don't have to worry about external state.
Check out various functional languages like F#, Haskell, and Scala. Scala treats functions as objects that have an apply() method, and you can store them in variables and pass them around like you can any other kind of object. I don't know that you can print out the definition of a Scala function as code though.
Update: I seem to recall that at least some Lisps allow you to pretty-print a function as code (eg, Scheme's pretty-print function).
This is the way spreadsheets work.
It is also related to call by name semantics for evaluating function arguments. Algol 60 had that, but it didn't catch on, too complicated to implement.
The programming language Lucid does this, although it calls x and y "streams" rather than functions.
The program would be written:
y
where
y = x + 4
end
And then you'd input:
x(0): 2
y = 6
x(1): 5
y = 7
Of course, Lucid (like most interesting programming languages) is fairly obscure, so I'm not surprised that nobody else found it. (or looked for it)
Try checking out F# here and on Wikipedia about Functional programming languages.
I myself have not yet worked on these types of languages since I've been concentrated on OOP, but will be delving soon once F# is out.
Hope this helps!
The closest I've seen of these have been part of Technical Analysis systems in charting components. (Tradestation, metastock, etc), but mainly they focus on returning multiple sets of metadata (eg buy/sell signals) which can be then fed into other functions that accept either meta data, or financial data, or plotted directly.
My 2c:
I'd say a language as you suggest would be highly confusing to say the least. Functions are generally r-values for good reason. This code (javascript) shows how enforcing functions as r-values increases readability (and therefore maintenance) n-fold:
var x = 2;
var y = function() { return x+2; }
alert(y());
x= 5;
alert(y());
Self makes no distinction between fields and methods, both are slots and can be accessed in exactly the same way. A slot can contain a value or a function (so those two are still separate entities), but the distinction doesn't matter to the user of the slot.
In Scala, you have lazy values and call-by-name arguments in functions.
def foo(x : => Int) {
println(x)
println(x) // x is evaluated again!
}
In some way, this can have the effect you looked for.
I believe the mathematically oriented languages like Octave, R and Maxima do that. I could be wrong, but no one else has mentioned them, so I thought I would.

Resources