Reassignment in ghci - haskell

Is it possible to reassign the same variable in ghci ? Of course this isn't possible in normal Haskell (at least without something like an IORef), but I was curious because the it variable in ghci that you get by enabling the :m option. With that enabled I get an experience where it is effectively reassignable by not binding the next expression to anything, e.g.
λ> 1 + 1
2
it :: Num a => a
λ> it
2
it :: Num a => a
λ> it + 1
3
it :: Num a => a
λ> it
3
it :: Num a => a
Is there a way to realize the same effect for an arbitrary named variable, not just the special it ?

Each new line in GHCi enters new, nested scope. Consider
> x = 1
> x
1
> foo y = x + y
> foo 41
42
> x = 7 -- new x
> x
7
> bar y = x + y -- refers to new x
> bar 41
48
> foo 41 -- still refers to the same old x binding
42
Second binding of x defines new same-named variable.
Naturally, it shadows the previous binding for that name, making it inaccessible in itself. Any other entity (like foo) which referenced it before though, will continue to hold that reference, no matter the shadowing for the newer, nested environments.
This follows the principle of immutability of values in Haskell: the foo remains the same.
One caveat:
> :{
x = 1
foo y = x + y
x = 7 -- error: conflicting definition
bar y = x + y
:}
causes an error, because lines entered in multiline mode belong to the same scope.
In other words the answer to your question is no, it would break the fundamental purity properties of Haskell.
it is not reassigned either, it is defined anew in each new nested environment, whenever there is any output, being bound to the output value:
> x
7
> it
7
> it_2 -- made a typo
error: Not in scope: `it_2'
> it+2 -- no previous output, same `it` in effect
9
> it+2 -- most recent `it` is 9
11
So you can always shadow your variable and create a new binding with the same name, but you can't change the old binding, because it is a part of history now, and the past can not be changed, by definition. It already happened.
Or you could create your own Haskell interpreter where you'd give a user an ability to "change" an old binding, but what would really happen is that a new copy of the interpreter would be spawned even "playing" all the recorded user actions at the prompt -- new definitions and all -- from that point on. Then the user would end up with a changed copy which would be oblivious to the existence of the first one. You could even kill the original at that point. Could this be considered as user having changed the past? The user's past hasn't changed, their time goes forward. The new copy's past was always what it is now, as far as it is concerned. The older original (copy?) is gone... A question to ponder.

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.

why isn't this incorrect indentation in haskell?

Why doesn't line 5 contain an indentation error. I expected to get a parse error on compilation. I expected that the + on line 5 would have to be aligned under the * in line 4.
module Learn where
x = 10
* 5
+ y -- why isn't this incorrect indentation
myResult = x * 5
y = 10
It compiles because there's no block there to consider.
Indentation only matters after where, let, do, case of.
These keywords start a block of things, and it is important to understand whether a line continues the previous entry, starts a new entry, or ends the block.
case f 5 of
A -> foo
32 -- continues the previous entry
B -> 12 -- starts a new entry
+ bar 43 -- ends the case
After = we do not need to split a block into entries: there's only a single expression. Hence no indentation rules apply.
This compiles because the definition of x was all to the right of the beginning of x. It's not important where each line starts as long as those lines are indented to the right of x.

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 [] :-)

haskell: factors of a natural number

I'm trying to write a function in Haskell that calculates all factors of a given number except itself.
The result should look something like this:
factorlist 15 => [1,3,5]
I'm new to Haskell and the whole recursion subject, which I'm pretty sure I'm suppoused to apply in this example but I don't know where or how.
My idea was to compare the given number with the first element of a list from 1 to n div2
with the mod function but somehow recursively and if the result is 0 then I add the number on a new list. (I hope this make sense)
I would appreciate any help on this matter
Here is my code until now: (it doesn't work.. but somehow to illustrate my idea)
factorList :: Int -> [Int]
factorList n |n `mod` head [1..n`div`2] == 0 = x:[]
There are several ways to handle this. But first of all, lets write a small little helper:
isFactorOf :: Integral a => a -> a -> Bool
isFactorOf x n = n `mod` x == 0
That way we can write 12 `isFactorOf` 24 and get either True or False. For the recursive part, lets assume that we use a function with two arguments: one being the number we want to factorize, the second the factor, which we're currently testing. We're only testing factors lesser or equal to n `div` 2, and this leads to:
createList n f | f <= n `div` 2 = if f `isFactorOf` n
then f : next
else next
| otherwise = []
where next = createList n (f + 1)
So if the second parameter is a factor of n, we add it onto the list and proceed, otherwise we just proceed. We do this only as long as f <= n `div` 2. Now in order to create factorList, we can simply use createList with a sufficient second parameter:
factorList n = createList n 1
The recursion is hidden in createList. As such, createList is a worker, and you could hide it in a where inside of factorList.
Note that one could easily define factorList with filter or list comprehensions:
factorList' n = filter (`isFactorOf` n) [1 .. n `div` 2]
factorList'' n = [ x | x <- [1 .. n`div` 2], x `isFactorOf` n]
But in this case you wouldn't have written the recursion yourself.
Further exercises:
Try to implement the filter function yourself.
Create another function, which returns only prime factors. You can either use your previous result and write a prime filter, or write a recursive function which generates them directly (latter is faster).
#Zeta's answer is interesting. But if you're new to Haskell like I am, you may want a "simple" answer to start with. (Just to get the basic recursion pattern...and to understand the indenting, and things like that.)
I'm not going to divide anything by 2 and I will include the number itself. So factorlist 15 => [1,3,5,15] in my example:
factorList :: Int -> [Int]
factorList value = factorsGreaterOrEqual 1
where
factorsGreaterOrEqual test
| (test == value) = [value]
| (value `mod` test == 0) = test : restOfFactors
| otherwise = restOfFactors
where restOfFactors = factorsGreaterOrEqual (test + 1)
The first line is the type signature, which you already knew about. The type signature doesn't have to live right next to the list of pattern definitions for a function, (though the patterns themselves need to be all together on sequential lines).
Then factorList is defined in terms of a helper function. This helper function is defined in a where clause...that means it is local and has access to the value parameter. Were we to define factorsGreaterOrEqual globally, then it would need two parameters as value would not be in scope, e.g.
factorsGreaterOrEqual 4 15 => [5,15]
You might argue that factorsGreaterOrEqual is a useful function in its own right. Maybe it is, maybe it isn't. But in this case we're going to say it isn't of general use besides to help us define factorList...so using the where clause and picking up value implicitly is cleaner.
The indentation rules of Haskell are (to my tastes) weird, but here they are summarized. I'm indenting with two spaces here because it grows too far right if you use 4.
Having a list of boolean tests with that pipe character in front are called "guards" in Haskell. I simply establish the terminal condition as being when the test hits the value; so factorsGreaterOrEqual N = [N] if we were doing a call to factorList N. Then we decide whether to concatenate the test number into the list by whether dividing the value by it has no remainder. (otherwise is a Haskell keyword, kind of like default in C-like switch statements for the fall-through case)
Showing another level of nesting and another implicit parameter demonstration, I added a where clause to locally define a function called restOfFactors. There is no need to pass test as a parameter to restOfFactors because it lives "in the scope" of factorsGreaterOrEqual...and as that lives in the scope of factorList then value is available as well.

How to test my haskell functions

I just started with Haskell and tried to do write some tests first. Basically, I want to define some function and than call this function to check the behavior.
add :: Integer -> Integer -> Integer
add a b = a+b
-- Test my function
add 2 3
If I load that little script in Hugs98, I get the following error:
Syntax error in declaration (unexpected `}', possibly due to bad layout)
If I remove the last line, load the script and then type in "add 2 3" in the hugs interpreter, it works just fine.
So the question is: How can I put calls of my functions in the same script as the function definition? I just want to load the script and be able to check if it does what I expect it to...I don't want to type them in manually all the time.
Others have said how to solve your immediate problem, but for testing you should be using QuickCheck or some other automated testing library.
import Test.QuickCheck
prop_5 = add 2 3 == 5
prop_leftIdentity n = add 0 n == n
Then run quickCheck prop_5 and quickCheck prop_leftIdentity in your Hugs session. QuickCheck can do a lot more than this, but that will get you started.
(Here's a QuickCheck tutorial but it's out of date. Anyone know of one that covers QuickCheck 2?)
the most beginner friendly way is probably the doctest module.
Download it with "cabal install doctest", then put your code into a file "Add.hs" and run "doctest Add.hs" from the command line.
Your code should look like this, the formatting is important:
module Add where
-- | add adds two numbers
--
-- >>> add 2 3
-- 5
-- >>> add 5 0
-- 5
-- >>> add 0 0
-- 0
add :: Integer -> Integer -> Integer
add a b = a+b
HTH Chris
Make a top level definition:
add :: Integer -> Integer -> Integer
add a b = a + b
test1 = add 2 3
Then call test1 in your Hugs session.
How can I put calls of my functions in the same script as the function definition? I just want to load the script and be able to check if it does what I expect it to...I don't want to type them in manually all the time.
In short, you can't. Wrap it in a function and call it instead. Your file serves as a valid Haskell module, and having "flying" expression is not a valid way to write it.
You seem to come from a scripting language background, but don't try treating Haskell as one of them.
If you have ghc installed, then the runhaskell command will interpret and run the main function in your file.
add x y = x + y
main = print $ add 2 3
Then on the command line
> runhaskell Add.hs
5
Not sure, but hugs probably has a similar feature to the runhaskell command. Or, if you load the file into the hugs interpreter, you can simply run it by calling main.
I was trying to do the same thing and I just made a function that ran through all my test cases (using guards) and returned 1 if they all passed and threw an error if any failed.
test :: Num b => a->b
test x
| sumALL [1] /= 1 = error "test failed"
| sumALL [0,1,2] /= 3 = error "test failed"
...
| otherwise = 1

Resources