recursion - Recursively dropping elements from list in Haskell -
right i'm working on problem in haskell in i'm trying check list particular pair of values , return true/false depending on whether present in said list. question goes follows:
define function called
after
takes list of integers , 2 integers parameters.after numbers num1 num2
should return true ifnum1
occurs in list ,num2
occurs afternum1
. if not must return false.
my plan check head of list num1
, drop it, recursively go through until 'hit' it. then, i'll take head of tail , check against num2
until hit or reach end of list.
i've gotten stuck pretty early, have far:
after :: [int] -> int -> int -> bool after x y z | y /= head x = after (drop 1 x) y z
however when try run such after [1,4,2,6,5] 4 5
format error. i'm not sure how word line such haskell understand i'm telling do.
any appreciated! :)
edit 1: error in question:
program error: pattern match failure: after [3,num_fromint instnum_v30 4] 3 (num_fromint instnum_v30 2)
try this:
after :: [int] -> int -> int -> bool after (n:ns) b | n == = ns `elem` b | otherwise = after ns b after _ _ _ = false
basically, function steps through list, element element. if @ point encounters a
(the first number), checks see if b
in remainder of list. if is, returns true
, otherwise returns false
. also, if hits end of list without ever seeing a
, returns false
.
Comments
Post a Comment