1
votes

I'm new with Haskell. I know that Hugs is old and is not supported anymore but my university still uses it.
Here is my code:

gio n = jako n ++ tazo n

jako [] = []
jako (a:b) = if a `mod` 2 == 1 then a:jako (tail b) else jako (tail b)

tazo [] = []
tazo (a:b) = if a `mod` 2 == 0 then a:tazo (tail b) else tazo (tail b)

What I'm trying to do is take an list, and return odd list united with even list. For example gio [1,2,3,4,5,6,7,8,9] = [1,3,5,7,9,2,4,6,8] But in my case it returns Program error: {tail []} or if the original lists length is even it returns only odd part list. For example: gio [1,2,3,4,5,6,7,8] = [1,3,5,7] it seems like when jako n is called it changes the list, it passes the list with reference or something like that. What can be changed to achieve the goal? P.S I don't need some library function that would do this, It needs to be done by using my functions. thanks.

2
Please use ctrl-k to format code blocks. And always add type signatures for any Haskell functions you're asking about, this makes it so much easier to see what's going on (both for us and for you!).leftaroundabout
sorry, I'll take that in mind next timeRasty
Have you tried removing all the tail b and using b directly? This is because b already is the tail of the input.chi
yes, It worked how stupid of me. Thank you very much! Post it as answer and I'll approve.Rasty
The prelude have odd :: Integral a => a -> Bool and even :: Integral a => a -> Bool alreadywizzup

2 Answers

1
votes

When the input is a:b, the b part is the tail, so there's no need to use tail b -- that would be the tail-of-the-tail, which can trigger a runtime error when the tail b is empty (i.e. the input is of length one). Further, even if the error were not an issue, taking the tail again skips over the next element of the list, which is wrong.

The solution is to remove tails from your code:

gio n = jako n ++ tazo n

jako [] = []
jako (a:b) = if a `mod` 2 == 1 then a:jako b else jako b

tazo [] = []
tazo (a:b) = if a `mod` 2 == 0 then a:tazo b else tazo b
0
votes
gio :: Integral a => [a] -> [a]
gio n = jako n ++ tazo n
  where
    jako [] = []
    jako (x:xs)
      | isOdd x     = x:jako xs
      | otherwise = jako xs
    tazo [] = []
    tazo (x:xs)
      | isEven x    = x:tazo xs
      | otherwise = tazo xs
    isEven n = mod n 2 == 0
    isOdd  n = mod n 2 /= 0