i've started studying functional programming in Haskell recently and was given some problems to solve, it asks to make your own versions of some system function for lists using recursion and basic system functions. the functions i need to write is:
!!
(nth item in a list)append
(joining lists together)subst
(substitution) e.g.subst 'x' 'y' ['q','x','r','x','s']
~>['q','y','r','x','y','s']
intersection
e.g.intersection [2,5,7] [9,7,3,5]
~>[5,7]
union
union e.gunion [2,5,7] [9,7,3,5]
~>[2,5,7,9,3]
reverse
e.g.reverse [4,5,6,7]
~>[7,6,5,4]
I started with the first one and wrote a definition like this:
nthelement :: Eq a => [a] -> a -> a
in imperative language i would make a counter variable (say i
) and use system function tail
to remove first element of list until i = n
. But as I learned that in functional you can only do constants I can't think of a way to decide when to stop recurring and return the element rather then recuring tail
function till the list is empty.
Please help me to figure this out. Any help on doing first function or any of them would be very nice. Thanks.
nthelement
does not needEq a
, and it doesn't take ana
next to the list. Example use would benthelement ['a','c','b'] 1 ~> 'c'
– Bergihead
ortail
. – Bergixs <<!!>> n = head . drop n $ xs
– Lol4t0Ord a
means thata
s are comparable -<
,==
,>
. What you meant is aNum
(arithmetic operations). What you actually need is an integral type, such asInteger
orInt
. And the basic problem you had that you've specified the index to be of the same type as the list elements. – Bergi