Haskell Increment by One

11,370

Solution 1

add1_list_comp = map succ

that simple

or, in your way

add1_list_comp xs = [x + 1| x <- xs]

the problem with your code is that

add1_list_comp [x] 

does pattern match on list with single item, that's why it fails on list with several items.

Solution 2

I see that the question has been answered, but perhaps I can explain a bit more. The argument of a function is pattern matched, and the general rules are

(x:xs) 

x is the head of the list and xs is the tail of the list, and potentially empty list

[]

empty list

[x] or (x:[]) 

are the same which is a list with only one variable

and a name with no constructor such as "[]", ":", "(,)" around can match anything, so if you want to match a special case, you should put the special case in front of the general pattern.

 length [] = 0
 length [x] = 1
 length (x : xs) = 1 + length xs

BTW, generally speaking, there will always be a higher order function when you want to do something with a list. for your case

 add1 xs = map (+1) xs 

is nicer and it took advantage of the built in library, and you can also do a point free version of it

 add1 = map (+1)

Solution 3

Well actually since the topic states "Increment by One" without defining what type is going to be incremented by one, just for the sake of a visitor ended up here lets give a solution which would increment any functor by one, which of course includes the list type. So;

List functor

*Main> fmap (+1) [1,2,3]
[2,3,4]

Maybe functor (id applies to Nothing)

*Main> fmap (+1) (Just 1)
Just 2

Either functor (id applies to Left _)

*Main> fmap (+1) (Right 2)
Right 3

IO functor

*Main> fmap ((+1) . read) getLine
2017
2018
Share:
11,370
Justin Tyler
Author by

Justin Tyler

Updated on June 04, 2022

Comments

  • Justin Tyler
    Justin Tyler almost 2 years

    Trying to create a Haskell program that increments every number in a list by one.

    module Add1List where
    add1_list_comp :: [Integer] -> [Integer]
    add1_list_comp [x] = [x + 1| x <- [x]]
    

    It works when I call this add1_list_comp [3] ... it gives me [4]

    But when I do add1_list_comp [3, 4, 5] ... it throws me an error saying

    "non-exhaustive patterns in function add1_list_comp"

    Any help would be much appreciated!