Why doesn’t this code go wrong, but it doesn’t return anything?

Asked

Viewed 50 times

2

I’m still learning Haskell (actually just started about 2 days ago) with a basic C# knowledge.

In this piece of code the code is supposed to iterate several times in a list and subtract the first value to the second until finished. The problem is that when I run the code it doesn’t make mistakes, but it goes into a kind of infinite loop, because nothing happens.

sub :: [Float] -> Float
sub [] = 0
sub (x : xs) = sub ( subtract (head xs) x : xs)

I also tried this code, but it just subtracted the first 2 values from the list. I know more or less why, but I don’t know how to solve.

sub :: [Float] -> Float
sub [] = 0
sub (x : xs) = subtract (head xs) x

Thanks for the help.

1 answer

0

The main missing point was to recall the sub function in the correct form. I don’t understand very well what you want to do, see if the iteration below is the expected result:

Input: [1,2,3,4]

1. [1,2,3,4] -- (2 - 1) (2° posição - 1° posição)
2. [1,1,3,4] -- (3 - 1) (3° posição - 2° posição)
3. [1,1,2,4] -- (4 - 2) (4° posição - 3° posição)
4. [1,1,2,2] -- Final

In this case we are subtracting the next position by the already subtracted result. If this is your need then the code is as follows:

sub :: [Int] -> [Int]
sub [] = []
sub (x:xs)
  | length xs == 0 = [x]
  | otherwise = [x] ++ sub ([y - x] ++ drop 1 xs)
  where y = head(xs)

main = do
  let list = [1,2,3,4]
  print $ sub list -- [1,1,2,2]

I’m using Guards (Similar to switch/case) that says what if the tail is size 0 returns the value itself (This is necessary because head(Xs) cannot receive an empty list and also helps in lists with only 1 value). If the tail of the list is greater than 0 I concateno x and use sub in a new list which is the concatenation of the subtraction made with the tail minus 1 element on the left. It’s a little confusing, but I’ll make the iterations easier:

Input: [1,2,3,4]

1. [1] ++ sub ([2 - 1, 3, 4])
2. [1] ++ sub ([3 - 1, 4])
3. [2] ++ sub ([4]) -- apenas 1 elemento retorna o elemento
4. [1,1,2,2] -- Final

Browser other questions tagged

You are not signed in. Login or sign up in order to post.