Home > OS >  Char -> Bool problems in filter function
Char -> Bool problems in filter function

Time:01-04

Right now I'm working on a program that removes everything but "a" in a text element just as a practice problem, here's my code.

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Char as C
import qualified Data.Text as T

removeNonAs :: T.Text -> T.Text
removeNonAs txt = T.filter ("a") txt

My problem is with the placeholder "a" in T.Filter. Every time I try to run the program it gives an error message saying (class) isn't Char -> Bool. I used to use elem` "a" which worked fine but then I added OverloadedStrings Which made it not work and give an "ambiguous type variable" error message. I am very confused with what made elem` "a" stop working, what the whole Char -> Bool thing is about, and what to do. If you could help me thanks.

CodePudding user response:

By checking the type signature of filter: filter :: (Char -> Bool) -> T.Text -> T.Text we know that filter accept one function and one Text, the function accepts Char and returns Bool then we can define removeNonAs like this:

import qualified Data.Char as C
import qualified Data.Text as T

removeNonAs :: String -> T.Text
removeNonAs = T.filter (=='a') . T.pack
-- usage:
removeNonAs "abcabcabc"
"aaa"

T.pack convert String to Text.

also you can define more general form of removeNonAs:

removeNonAsGeneral :: Char -> String -> T.Text
removeNonAsGeneral a = T.filter (==a) . T.pack
-- usage:
removeNonAsGeneral 'a' "abcdabcdabcd"
"aaa"
  •  Tags:  
  • Related