3

Is there a way to use the filter function on Strings, this way:

filter (=="!") "!!some!!_!!string!!"

should output "some_string" (case above). Right now all i get is a type error:

Couldn't match expected type `[Char]' against inferred type `Char'

If i change the second filter argument type to ["!!some!!_!!string!!"], the type error disappears, yet only an empty list is outputted. (Not exactly what i want)

I thought that strings were lists but obviously "!!some!!_!!string!!" isn't regarded as a list but as a char.

Any hints someone ?

1 Answer 1

12
Prelude> filter (/='!') "!!some!!_!!string!!"
"some_string"

The type of filter is (a -> Bool) -> [a] -> [a]. Since the 2nd argument is a String = [Char], meaning [a] = String = [Char], we infer that a must be a Char. The function therefore must take a Char as input. Therefore, you need to use '!', not "!".

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Say what you will about Hindley-Milner-ish type systems, but they do make type signatures more useful.
i'm not saying anything, i just want my code to work easily. And strong typing combined to functional programming has its pitfalls.
@kiltek Pitfalls like having to say what you mean? This isn't a nit-picky error. You were asking it to remove all elements of a list that matched something that couldn't possibly be an element of the list. That's a bug. The type system caught it at compile time. That seems like a pretty good deal to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.