Reputation: 4240
I'm trying to use regex to filter all the strings in a list of strings. Here is my function which takes a string and filters it
let filterWord wordToFilter =
Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");
Since I want to apply that function to every element in my list of strings, it seems that using List.map would make sense. Here is my attempt at using map
let filteredWords = unfilteredWords |> List.map(fun x -> filterWord(x));
I was hoping that line would apply my filter function to every string in my list (unfilteredWords is a list of strings) but instead I get a syntax error saying
"Type mismatch. Expecting a
string [] -> 'a
but given a
'b list -> 'c list
The type 'string []' does not match the type ''a list'"
And have no idea why. Here is the full code
open System;
open System.IO;
open System.Text.RegularExpressions;
(*Tests if an element is in a list*)
let isInList elementToFind listToCheck =
List.fold(fun a b -> a || b = elementToFind) false listToCheck;
(*Takes a string and filters it down to common text characters*)
let filterWord wordToFilter =
Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");
(*Main method of the program*)
[<EntryPoint>]
let main argsv =
let input = File.ReadAllText("Alice in Wonderland.txt"); //Reads all the text into a single string
let unfilteredWords = input.Split(' ');
let filteredWords = unfilteredWords |> List.map(fun x -> filterWord(x));
0;
Any help would be appreciated, thanks!
EDIT: Apparently changing the value of unfilteredWords to a hard coded string array fixes it. Problem is I have no idea how to make it work with split.
Upvotes: 3
Views: 2250
Reputation: 627128
Here is a fix: use Array.map
instead of List.map
.
Note that you can use F# .Split [|' '|]
instead of .Split(' ')
.
let input = "### $$$ Alice In Wonderland ,,,,";
let unfilteredWords = input.Split [|' '|]
let filteredWords = unfilteredWords |> Array.map(fun x -> filterWord(x));
printfn "%A" filteredWords;
See IDEONE demo
The output for the sample string in my demo is
[|""; ""; "Alice"; "In"; "Wonderland"; ""|]
Upvotes: 2
Reputation: 2503
Seeing this question: F# Using List.map on an array of strings
I would guess you should use Array.map or Seq.map instead of List.map
Upvotes: -1