Triangular Lists in Haskell? -
i have write function (without using preloaded functions) decides if list of ints triangular or not, , triangular mean if increases number , decreases, example:
[2,4,5,7,4,3] also: [], [1], [1,1], [1, 2, 3], [3, 2, 1], [1, 2, 2], [2, 2, 1] (so non-strict increasing , decreasing)
i came dont know next, advice appreciated:
ex :: [int] -> bool ex [] = true ex (x:xs) |
i’ll try explain code while develop it. problem can split in two: detecting increasing part of list, , decreasing part of list. key idea of working lists in haskell (if don’t have empty list @ hand) @ head of list, , tail, , try go through list in order.
so let write function detect whether list non-strictly decreasing first. there of course several ways, this. let’s try recursive approach without parameters. had start
dec :: [int] -> bool dec [] = true
now lets continue pattern matching. next largest list not empty list 1 element, decreasing:
dec [x] = true
the next step interesting. if have list 2 elements (x
, y
) @ beginning (and possibly more) list de decreasing, x >= y
needs hold, remaining list, starting @ y
, needs decreasing. sufficient, have write out
dec (x:y:rest) = x >= y && dec (y:res)
and thats it!
now exercise function, can same thing. difference once list fails increasing, allow check if the list might decreasing point on:
ex :: [int] -> bool ex [] = true ex [x] = true ex (x:y:rest) = (x <= y && ex (y:res)) || dec (x:y:rest)
i hope explanation of how came write code helps next exercises. note there many other, more efficient, ways solve this.
Comments
Post a Comment