Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm having trouble writing a simple function in Haskell... It is meant to calculate the sum of numbers from 1 to n. I'm not allowed to use if statements because my teacher want us to focus on functional programing. Any help would be appreciated. Thanks!
summation :: Integer -> Integer
summation n
| n > 1 = n + summation(n-1)
| n == 1 = 1
This is the output from GHCi:
clase4.hs:13:28: error:
Variable not in scope: (?) :: Integer -> Integer -> Integer
Failed, modules loaded: none.
Line 13 is:
| n > 1 = n + summation(n-1)
I've commented everything else in the file and I still get that error. I cannot see '?' anywhere. These are the screen captures:
In your source file clase4.hs, the character you think is a standard ASCII minus sign in the expression n-1 isn't. Instead, you've probably used some other unicode character, like an "en dash" or something that only looks like a minus sign (perhaps because you've edited the file in something weird like Microsoft Word or copied and pasted the code from some source that was messing with the characters).
Haskell is printing the invalid character as a "?" because, as far as it can tell, your output terminal doesn't support the encoding necessary to display the bad character. (This is a common problem when running Haskell in a Windows environment, though it might happen on other platforms if things were set up strangely.)
Open the source file with a proper text editor, highlight the "minus sign" and re-type it on your keyboard. On a Spanish keyboard, this should be the key to the left of the bottom-right shift key; on a US keyboard, it's to the right of the zero key.
If that fails, try copying and pasting your own program above from Stack Overflow into a brand new text file and compile that -- copying and pasting from your question is working fine for the rest of us.
It looks to me that there are two problems here:
your recursive call calls sumatoria whereas your function is summation;
you check for n > 1 and n == 1 which is rather unsafe.
We can resolve the problems by subsituting sumatoria by summation, and make the guards more safe:
summation :: Integer -> Integer
summation n
| n >= 1 = n + summation (n-1)
| otherwise = 0
Now it should work. We use otherwise = 0 such that if we enter 0 or a negative number, we obtain 0.
Nevertheless we can still improve this function. First of all, we should not restrict ourselves to only Integers. We can use any kind of Numeric type a that is Orderable. So we can rewrite it to:
summation :: (Num a, Ord a) => a -> a
summation n
| n > 1 = n + summation (n-1)
| otherwise = 0
And furthermore the sum of 1..n or 0..n can be calculated by using:
n
---
\ n * (n+1)
/ i = ---------
--- 2
i=1
So we can write it as:
summation :: Integral a => a -> a
summation n = div (n * (n+1)) 2
The div :: Integral a => a -> a -> a requires a to be Integral. In case the multiplication, increment, and division are all O(1) operations, this is an O(1) function now.
Finally note that besides using recursion, you can also use functions like sum. In that case you could have used:
summation :: (Enum a, Num a) => a -> a
summation n = sum [1..n]
Related
I'm learning Haskell, running through the lectures:
http://www.cis.upenn.edu/~cis194/spring13/
I've got:
module HanoiDisk(HanoiDisk, hanoiDisk) where
import Control.Exception
data HanoiDisk = HanoiDisk' Integer deriving (Show)
hanoiDisk :: Integer -> HanoiDisk
hanoiDisk n = assert (n >= 1) $ HanoiDisk' n
This works, but if i have:
main = do
print(show (hanoiDisk (-3))
I only get an error during run-time and not at compile-time.
I'm pretty keen to understand how to eliminate run-time exceptions entirely.
Can anyone provide an alternative approach?
Thanks
Haskell checks types when compiling a code, not values. To make types depend on values is the job of "dependent types". It is an advanced topic.
The other way to achieve this is to make your hanoiDisk work not with Integers, but with some "PositiveInteger" type which can not possibly be negative (or 0 as well..?). It is a more basic approach.
There will be nothing to assert -- it should be impossible for you to even write down a negative value with this type. You'll have to make this type an instance of Num, Eq, Ord, and Show (maybe Enum as well).
The usual way is to define
data Nat = Z | S Nat
deriving (Eq, Show)
From what I understand, you want a way to "fail nicely" when someone applies the function hanoiDisk to an argument that's less than 1.
As a commenter stated, doing that at compile time is outside the scope of basic Haskell and you shouldn't need it in your day-to-day code!
You can definitely "fail nicely" by using the Either a b datatype.
The idea is that if you have a function hanoiDisk :: Integer -> HanoiDisk that takes an Integer and is supposed to return a HanoiDisk value if the input is "good" and an error value of some sort when the input is "bad", you can encode that using alternate constructors.
The constructors for the Either a b datatype are Left a and Right b where
an error output would be of the form Left a and a good output would be of the form Right b. Let's rewrite your function using this.
hanoiDisk :: Integer -> Either String HanoiDisk
hanoiDisk n = if n >= 1
then Right (HanoiDisk' n)
else Left "a hanoi disk must be least 1"
(Probably) More Appropriate Answer
Let's discuss the simpler problem of constructing numbers that must be nonnegative (as opposed to positive) in a way that's acceptable to the compiler.
I think the problem is tied to the way numbers are parsed by the compiler. Any time you use the symbols '0', '1', '2', '3', '4', ..., '9' to represent digits in your program the language parser expects the end result to conform to a type like Int, Double, etc. and so when you use these symbols you open yourself up to the possibility that someone might prepend a '-' to the sequence of digits and turn your nonnegative number into a negative one.
Let's make a new module called Natural which will allow us to create positive numbers. In it, we define "aliases" for the symbols '0',...,'1' using the first two letters of each symbol's name (eg. tw for '2'). Since humans write natural numbers using the decimal system, we create a data type called Natural that takes two arguments - the first digit of the number we're representing and then a list of subsequent digits. Finally, we selectively export functions from the module to prohibit "misuse" by users.
module Natural (ze,on,tw,th,fo,fi,si,se,ei,ni,Natural(..)) where
newtype Digit = Digit Int
ze = Digit 0
on = Digit 1
tw = Digit 2
th = Digit 3
fo = Digit 4
fi = Digit 5
si = Digit 6
se = Digit 7
ei = Digit 8
ni = Digit 9
data Natural = Nat Digit [Digit]
As an example, the natural number 312 would be represented as Nat th [on,tw].
Any module importing Natural would only have access to the functions that we export, so attempts to use anything else to define a value of type Natural would result in compile errors. Furthermore, since we didn't export the Digit constructor there's no way for importers to define their own values for the Digit type.
I'm leaving out definitions of the instances for Num, Integral, Eq, Ord, etc. because I don't think they would add more to my explanation.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am learning a haskell for a few days and the laziness is something like buzzword. Because of the fact I am not familiar with laziness ( I have been working mainly with non-functional languages ) it is not easy concept for me.
So, I am asking for any excerise / example which show me what laziness is in the fact.
Thanks in advance ;)
In Haskell you can create an infinite list. For instance, all natural numbers:
[1,2..]
If Haskell loaded all the items in memory at once that wouldn't be possible. To do so you would need infinite memory.
Laziness allows you to get the numbers as you need them.
Here's something interesting: dynamic programming, the bane of every intro. algorithms student, becomes simple and natural when written in a lazy and functional language. Take the example of string edit distance. This is the problem of measuring how similar two DNA strands are or how many bytes changed between two releases of a binary executable or just how 'different' two strings are. The dynamic programming algorithm, expressed mathematically, is simple:
let:
• d_{i,j} be the edit distance of
the first string at index i, which has length m
and the second string at index j, which has length m
• let a_i be the i^th character of the first string
• let b_j be the j^th character of the second string
define:
d_{i,0} = i (0 <= i <= m)
d_{0,j} = j (0 <= j <= n)
d_{i,j} = d_{i - 1, j - 1} if a_i == b_j
d_{i,j} = min { if a_i != b_j
d_{i - 1, j} + 1 (delete)
d_{i, j - 1} + 1 (insert)
d_{i - 1, j - 1} + 1 (modify)
}
return d_{m, n}
And the algorithm, expressed in Haskell, follows the same shape of the algorithm:
distance a b = d m n
where (m, n) = (length a, length b)
a' = Array.listArray (1, m) a
b' = Array.listArray (1, n) b
d i 0 = i
d 0 j = j
d i j
| a' ! i == b' ! j = ds ! (i - 1, j - 1)
| otherwise = minimum [ ds ! (i - 1, j) + 1
, ds ! (i, j - 1) + 1
, ds ! (i - 1, j - 1) + 1
]
ds = Array.listArray bounds
[d i j | (i, j) <- Array.range bounds]
bounds = ((0, 0), (m, n))
In a strict language we wouldn't be able to define it so straightforwardly because the cells of the array would be strictly evaluated. In Haskell we're able to have the definition of each cell reference the definitions of other cells because Haskell is lazy – the definitions are only evaluated at the very end when d m n asks the array for the value of the last cell. A lazy language lets us set up a graph of standing dominoes; it's only when we ask for a value that we need to compute the value, which topples the first domino, which topples all the other dominoes. (In a strict language, we would have to set up an array of closures, doing the work that the Haskell compiler does for us automatically. It's easy to transform implementations between strict and lazy languages; it's all a matter of which language expresses which idea better.)
The blog post does a much better job of explaining all this.
So, I am asking for any excerise / example which show me what laziness is in the fact.
Click on Lazy on haskell.org to get the canonical example. There are many other examples just like it to illustrate the concept of delayed evaluation that benefits from not executing some parts of the program logic. Lazy is certainly not slow, but the opposite of eager evaluation common to most imperative programming languages.
Laziness is a consequence of non-strict function evaluation. Consider the "infinite" list of 1s:
ones = 1:ones
At the time of definition, the (:) function isn't evaluated; ones is just a promise to do so when it is necessary. Such a time would be when you pattern match:
myHead :: [a] -> a
myHead (x:rest) = x
When myHead ones is called, x and rest are needed, but the pattern match against 1:ones simply binds x to 1 and rest to ones; we don't need evaluate ones any further at this time, so we don't.
The syntax for infinite lists, using the .. "operator" for arithmetic sequences, is sugar for calls to enumFrom and enumFromThen. That is
-- An infintite list of ones
ones = [1,1..] -- enumFromThen 1 1
-- The natural numbers
nats = [1..] -- enumFrom 1
so again, laziness just comes from the non-strict evaluation of enumFrom.
Unlike with other languages, Haskell decouples the creation and definition of an object.... You can easily watch this in action using Debug.Trace.
You can define a variable like this
aValue = 100
(the value on the right hand side could include a complicated evaluation, but let's keep it simple)
To see if this code ever gets called, you can wrap the expression in Debug.Trace.trace like this
import Debug.Trace
aValue = trace "evaluating aValue" 100
Note that this doesn't change the definition of aValue, it just forces the program to output "evaluating aValue" whenever this expression is actually created at runtime.
(Also note that trace is considered unsafe for production code, and should only be used to debug).
Now, try two experiments.... Write two different mains
main = putStrLn $ "The value of aValue is " ++ show aValue
and
main = putStrLn "'sup"
When run, you will see that the first program actually creates aValue (you will see the "creating aValue" message, while the second does not.
This is the idea of laziness.... You can put as many definitions in a program as you want, but only those that are used will be actually created at runtime.
The real use of this can be seen with objects of infinite size. Many lists, trees, etc. have an infinite number of elements. Your program will use only some finite number of values, but you don't want to muddy the definition of the object with this messy fact. Take for instance the infinite lists given in other answers here....
[1..] -- = [1,2,3,4,....]
You can again see laziness in action here using trace, although you will have to write out a variant of [1..] in an expanded form to do this.
f::Int->[Int]
f x = trace ("creating " ++ show x) (x:f (x+1)) --remember, the trace part doesn't change the expression, it is just used for debugging
Now you will see that only the elements you use are created.
main = putStrLn $ "the list is " ++ show (take 4 $ f 1)
yields
creating 1
creating 2
creating 3
creating 4
the list is [1,2,3,4]
and
main = putStrLn "yo"
will not show any item being created.
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.
I've got a problem about to write a function to find the longest word in a text.
Input: A string with a lot of word. Ex: "I am a young man, and I have a big house."
The result will be 5 because the longest words in the text have 5 letters (young and house).
I've just started to learn Haskell. I've tried:
import Char
import List
maxord' (str:strs) m n =
if isAlpha str == True
then maxord'(strs m+1 n)
else if m >= n
then maxord'(strs 0 m)
else maxord'(strs 0 n)
maxord (str:strs) = maxord' (str:strs) 0 0
I want to return n as the result but I don't know how to do it, and it seems there is also something wrong with the code.
Any help? Thanks
Try to split your task into several subtasks. I would suggest splitting it like this:
Turn the string into a list of words. For instance, your example string becomes
["I","am","a","young","man","and","I","have","a","big","house"]
map length over the list. This calculates the word lengths. For example, the list in step 1 becomes
[1,2,1,5,3,3,1,4,1,3,5]
Find the word with the highest number of characters. You could use maximum for this.
You can compose those steps using the operator (.) which pipes two functions together. For instance, if the function to perform step 1 is called toWords, you can perform the whole task in one line:
maxord = maximum . map length . toWords
The implementation of toWords is left as an excercise to the reader. If you need help, feel free to write a comment.
There are several issues here. Let's start with the syntax.
Your else parts should be indented the same or more as the if they belong to, for example like this:
if ...
then ...
else if ...
then ...
else ...
Next, your function applications. Unlike many other languages, in Haskell, parentheses are only used for grouping and tuples. Since function application is so common in Haskell, we use the most lightweight syntax possible for it, namely whitespace. So to apply the function maxord' to the arguments strs, m+1 and n, we write maxord' strs (m+1) n. Note that since function application has the highest precedence, we have to add parentheses around m+1, otherwise it would be interpreted as (maxord' strs m) + (1 n).
That's it for the syntax. The next problem is a semantic one, namely that you have recursion without a base case. Using the pattern (str:strs), you have specified what to do when you have some characters left, but you've not specified what to do when you reach the end of the string. In this case, we want to return n, so we add a case for that.
maxord' [] m n = n
The fixed maxord' is thus
maxord' [] m n = n
maxord' (str:strs) m n =
if isAlpha str == True
then maxord' strs (m+1) n
else if m >= n
then maxord' strs 0 m
else maxord' strs 0 n
However, note that this solution is not very idiomatic. It uses explicit recursion, if expressions instead of guards, comparing booleans to True and has a very imperative feel to it. A more idiomatic solution would be something like this.
maxord = maximum . map length . words
This is a simple function chain where words splits up the input into a list of words, map length replaces each word with its length, and maximum returns the maximum of those lengths.
Although, note that it's not the exact same as your code, since the words function uses slightly different criteria when splitting the input.
There are a couple of problems
There is no termination for you recursion. You want to return n when you processed the whole input.
maxord' [] _ n = n
Syntax:
maxord'(strs 0 m)
this means that call apply strs with parameters 0 and m, and then use that as an argument to maxord. What you wan't to do is this:
maxord' strs 0 m
m+1 should be (m+1).
You might want to process empty strings, but maxord doesn't allow it.
maxord s = maxord' s 0 0
That should do it. There are a couple of subtleties. maxord' shoudln't leak out to the namespace, use where. (max m n) is a lot more concise than the if-then-else you use. And check the other answers to see how you can build your solution by wiring builtin things together. Recursions are a lot harder to read.
I am fairly new to Haskell but do get most of the basics. However there is one thing that I just cannot figure out. Consider my example below:
example :: Int -> Int
example (n+1) = .....
The (n+1) part of this example somehow prevents the input of negative numbers but I cannot understand how. For example.. If the input were (-5) I would expect n to just be (-6) since (-6 + 1) is (-5). The output when testing is as follows:
Program error: pattern match failure: example (-5)
Can anyone explain to me why this does not accept negative numbers?
That's just how n+k patterns are defined to work:
Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise.
The point of n+k patterns is to perform induction, so you need to complete the example with a base case (k-1, or 0 in this case), and decide whether a parameter less than that would be an error or not. Like this:
example (n+1) = ...
example 0 = ...
The semantics that you're essentially asking for would be fairly pointless and redundant — you could just say
example n = let n' = n-1 in ...
to achieve the same effect. The point of a pattern is to fail sometimes.