list - Haskell <<loop>> -
with getindex xs y want index of first sublist in xs length greater y.
the output is:
[[],[4],[4,3],[3,5,3],[3,5,5,6,1]] aufgabe6: <<loop>> why getindex not work?
import data.list -- die sortierfunktion -- mycompare b | length < length b = lt | otherwise = gt sortlist :: [[a]] -> [[a]] sortlist x = sortby mycompare x -- die indexfunktion -- getindex :: [[a]] -> int -> int getindex [] y = 0 getindex (x:xs) y | length x <= y = 1 + getindex xs y | otherwise = 0 (x:xs) = sortlist (x:xs) main = print (sortlist [[4],[3,5,3],[4,3],[3,5,5,6,1],[]]) print (getindex [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 2)
getting terminate
the problem in case
getindex (x:xs) y | length x <= y = 1 + getindex xs y | otherwise = 0 (x:xs) = sortlist (x:xs) you're confusing (x:xs) which. should instead do
getindex zs y | length x <= y = 1 + getindex xs y | otherwise = 0 (x:xs) = sortlist zs giving
main> main [[],[4],[4,3],[3,5,3],[3,5,5,6,1]] 3 *main> getindex [[],[2],[4,5]] 1 2 *main> getindex [[],[2],[4,5]] 5 3 this gives number of first list of length @ least y in sorted list, answers question "how many lists of length @ y in original?"
how can find out other facts?
if want position original list, can tag entries position, using zip:
*main> zip [1..] [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] [(1,[4]),(2,[3,5,3]),(3,[4,3]),(4,[3,5,5,6,1]),(5,[])] let's make utility function working those:
haslength likethis (_,xs) = likethis (length xs) we can use this:
*main> haslength (==4) (1,[1,2,3,4]) true *main> filter (haslength (>=2)) (zip [1..] ["","yo","hi there","?"]) [(2,"yo"),(3,"hi there")] which means it's easy write function gives index of first list of length longer y:
whichislongerthan xss y = case filter (haslength (>y)) (zip [1..] xss) of [] -> error "nothing long enough" -- change 0 or (length xss + 1) if prefer (x:xs) -> fst x this gives us
*main> whichislongerthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 2 2 *main> whichislongerthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 3 4 *main> whichislongerthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 0 1 shorter?
but can similar tricks:
whichisshorterthan xss y = case filter (haslength (<y)) (zip [1..] xss) of [] -> error "nothing short enough" -- change 0 or (length xss + 1) if prefer (x:xs) -> fst x so get
*main> whichisshorterthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 2 1 *main> whichisshorterthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 1 5 *main> whichisshorterthan [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 0 *** exception: nothing short enough generalised
let's pull out common theme there:
whichlength :: (int -> bool) -> [[a]] -> int whichlength likethis xss = case filter (haslength likethis) (zip [1..] xss) of [] -> error "nothing found" -- change 0 or (length xss + 1) if prefer (x:xs) -> fst x so can do
*main> whichlength (==5) [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 4 *main> whichlength (>2) [[4],[3,5,3],[4,3],[3,5,5,6,1],[]] 2
Comments
Post a Comment