F#在字符串数组上使用List.map [英] F# Using List.map on an array of strings

查看:137
本文介绍了F#在字符串数组上使用List.map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用F#的List.map函数来调用我写入数组中每个字符串的函数。这里是我写的函数

pre $ $ $ $ $ $ b让filterWord wordToFilter =
Regex.Replace(wordToFilter,[^ a-zA-Z0-9 /!\'?.-],);

以下是我称之为的主要方法

 (*程序的主要方法*)
[< EntryPoint>]
let main argsv =
let input = File.ReadAllText (Alice in Wonderland.txt); //将所有文本读入单个字符串
let unfilteredWords = input.Split('');
let filteredWords = unfilteredWords |> List.map(fun x - > filterWord(x));
0;

问题是我的List.map调用中出现语法错误,说

 错误类型不匹配。期待
字符串[] - > 'a
但给出
'b列表 - > 'c list
'string []'类型与列表'



不匹配将input.split更改为硬编码的字符串数组修复了错误,因此它与F#没有实现输入的结果有关.split可以与map函数一起使用,因为它是一个字符串数组。我只是不知道如何改变代码,因此它完成了我想完成的任务。我相对较新的F#,所以我可以得到任何帮助将不胜感激!

解决方案


F#没有实现input.split的结果,可以与map函数一起使用,因为它是一个字符串数组

List.map 可用于 list s,所以F#意识到结果不能与<$ c $一起使用C> List.map 。使用 Array.map (它对数组起作用)。

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!

解决方案

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.

这篇关于F#在字符串数组上使用List.map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆