简体   繁体   English

在Haskell中用数字替换字符

[英]Replacing characters with numbers in Haskell

I have started to do the questions on Project Euler regarding lists of names which need to be replaced with their corresponding position in the alphabet. 我已经开始在Euler项目上进行有关名称列表的问题,这些名称需要替换为字母中的相应位置。 In Problem 22 I need to replace, the letters with numbers: 问题22中,我需要用数字替换字母:

names = ["MARY","PATRICIA","LINDA"....
replace = ??????
char2num a = map replace a
score (a,b) = a * (sum $ map char2num b)
answer = sum $ map score (zip [1..] (sort names))

What I cannot find is how to replace the characters with their place in the alphabet. 我找不到的是如何用字母在字母表中的位置替换字符。 How would I go about making something to do the replace function (preferably not regex)? 我将如何做一些替换功能(最好不是正则表达式)?

The ord function in the Data.Char module gives an integer code for each character. Data.Char模块中的ord函数为每个字符提供一个整数代码。 Given that, this would be the function you're looking for: 鉴于此,这就是您要寻找的功能:

import Data.Char

replace :: Char -> Int
replace c = ord c - ord 'A' + 1

I'm not sure if ord c will return the ASCII code for a character, or the unicode codepoint, or if the result is machine dependent. 我不确定ord c是否会返回字符的ASCII代码或unicode代码点,或者结果是否与机器有关。 To abstract from that, we simply subtract the code for 'A' from the result, and add 1 because we want the alphabet to start at 1 instead of 0 . 为了对此进行抽象,我们只需从结果中减去'A'的代码,然后加上1因为我们希望字母从1而不是0

An easy way to find to find such a function is Hoogle . 找到这种功能的一种简单方法是Hoogle
There you can search for functions in the standard Haskell packages by entering its type. 您可以在其中输入其类型在标准Haskell软件包中搜索功能。 In this case ord is the second result when searching for Char -> Int . 在这种情况下, ord是搜索Char -> Int时的第二个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM