Increasing Haskell by one
Attempting to create a Haskell program that increments each 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 it add1_list_comp [3]
... it gives me[4]
But when I do add1_list_comp [3, 4, 5]
... it throws an error:
"non-exhaustive templates in add1_list_comp"
Any help would be greatly appreciated!
source to share
I see that the question has been answered, but maybe I can explain a little more. The function argument matches the pattern, and the general rules
(x:xs)
x is the head of the list and xs is the tail of the list and a potentially empty list
[]
empty list
[x] or (x:[])
is the same list that contains only one variable
and a name without a constructor such as "[]", ":", "(,)" can match anything, so if you want to match a special case, you must put a special case in front of the general figure.
length [] = 0
length [x] = 1
length (x : xs) = 1 + length xs
By the way, there will always be a higher order function if you want to do something with the list. for your case
add1 xs = map (+1) xs
nicer and he took advantage of the built-in library and you can also make it a free version
add1 = map (+1)
source to share
Ok, since this article states "Increment by One" without specifying which type will increase by one, just for the sake of the visitor to be here, let's give a solution that will increase any functor by one, which from the course includes list type. Thus,
Feature List
*Main> fmap (+1) [1,2,3]
[2,3,4]
Maybe a functor ( id
refers to Nothing
)
*Main> fmap (+1) (Just 1)
Just 2
Any functor ( id
applies to Left _
)
*Main> fmap (+1) (Right 2)
Right 3
IO functor
*Main> fmap ((+1) . read) getLine
2017
2018
source to share