F# Using List.map on an array of strings

2019-08-09 07:10发布

问题:

I'm trying to use F#'s List.map function to call a function I've written on every string in the array. Here is the function I've written

(*Takes a string and filters it down to common text characters*)
let filterWord wordToFilter = 
    Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");

and here is my main method where I call it

(*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;

The problem is I am getting a syntax error at my List.map call saying

Error       Type mismatch. Expecting a
    string [] -> 'a    
but given a
    'b list -> 'c list    
The type 'string []' does not match the type ''a list'  

Changing input.split to a hard coded string array fixes the error so it has something to do with F# not realizing the result of input.split can be used with the map function as it's a string array. I just don't know how to change the code so it accomplishes what I want to accomplish. I'm relatively new to F# so any help I can get would be greatly appreciated!

回答1:

F# not realizing the result of input.split can be used with the map function as it's a string array

List.map works on lists, so F# realizes the result can't be used with List.map. Use Array.map (which works on arrays) instead.