Haskell List Comprehensions -
i'm attempting haskell question i'm trying learn haskell.
the question gives me following type definitions:
type word = string
type line = [word]
type book = [line]
the question asks me define function index :: word -> book -> [int] takes word , book, , returns line numbers words appear on. eg:
index "example" [["example", "town"], ["example", "cat", "this"]] = [1,2]
so far have used zip book [1 .. length book] attach line numbers each line, give me
[(["example","town"],1),(["example","cat","this"],2)]
how extract line numbers? assuming use list comprehensions i'm not sure how it.
the general list comprehensions scheme these things is
g xs = [i | (x,i) <- zip xs [1..], pred x] pred predicate acting on elements of xs, input list; pass test, original indices included in output. of course can done higher order functions, as
g xs = map snd . filter (pred . fst) . (`zip` [1..]) $ xs (.) function composition operator: pred . fst == (\p -> pred (fst p)). above line written
g xs = map snd . filter (\(x,i) -> pred x) . (`zip` [1..]) $ xs whatever more readable you.
Comments
Post a Comment