質問

I'm totaly new with Haskell and I'm freaking out soon. ;-)

I need to create a function that takes lists of strings and deletes every word with * - + in it and all letter should be lowercase in the end.

Right now I got this:

list3 [] = []
list3 xs = map (filter (/='*' )) xs

I'm really sure it's not hard, but I just don't understand how I can delete not only one single * but a whole word with * in it. Also I don't get how I can put - and + into the filter function.

Example: list3 ["Tree-House", "CAT", "*Haskell-"] should output: ["cat"]

Thank you! I really appreciate your help.


And how can I put everything on lowercase? I tried like this, but I get a type error.

list3 xs = toLower (filter (not.any (`elem` "*-+")) xs)
役に立ちましたか?

解決 2

This problem could be solved step by step:

  1. define a function to check wether there is any occurrence of any character of a string in another string

    isInclude es xs = or $ map (\e -> e `elem` xs) es
    

    for every element in es you want to check, such as '*', '-', or '+', if it occurs in xs, that lambda abstraction (\e -> eelemxs) will return true. If any of that lambda abstractions is true, isInclude will be true.

    That isInclude can also be implemented like this

    isInclude es xs = or $ map (flip elem xs) es
    

    or

    isInclude es xs = or $ map (`elem` xs) es
    
  2. now you can find out all those strings in a list of string that do not include any of these characters

    filter (not . isInclude "*-+") ls
    

    here ls is a list of string

  3. finally, you can map toLower from Data.Char to every string to convert its characters to lower case

    list3 ls = map (map toLower) $ filter (not . isInclude "*-+") ls
    

他のヒント

You want to filter the outer list, not each individual string. That is why you are filtering out only individual character, not entire words.

To filter out words containing *

list3 = filter (not(elem '*'))

To filter out words containing any of * + - you need to change your predicate. In this case, we want to find words that contain * - or +, so we use the predicate

any (`elem` "*-+")

but that would filter out words not containing those characters and we want the opposite of that, so we instead write:

list3 = filter (not.any (`elem` "*-+"))

To then make all characters lowercase, you can map toLower over each string.

import Data.Char (toLower)
list3 xs = map (map toLower) $ filter (not.any (`elem` "*-+")) xs
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top