常量的模式匹配

swa*_*lay 0 syntax haskell functional-programming pattern-matching

所以我有这些常量FilePath变量(字符串)

s1 , s2 , s3 , s4 ... :: Filepath
s1 = "help.txt"
s2 = "sljdfn"
-- ...
Run Code Online (Sandbox Code Playgroud)

而且我有一个函数接受这些文件路径之一并返回一个int值。

positionInList:: Filepath -> Int
positionInList s1 = 1
positionInList s2 = 2
-- ...
Run Code Online (Sandbox Code Playgroud)

但是,在编译时会出现模式匹配冗余警告,并且程序运行异常,所以我认为这是问题所在。我将如何解决呢?

chi*_*chi 7

您必须在==这里使用:

positionInList:: Filepath -> Int
positionInList s | s == s1 = 1
                 | s == s2 = 2
.....
Run Code Online (Sandbox Code Playgroud)

否则,positionInList s1 = ...引入in s1作为与任何字符串匹配的局部变量。xpositionInList x = ...

或者,使用库函数:

import Data.List

positionInList:: Filepath -> Int
positionInList s = case elemIndex s [s1,s2,s3,....] of
   Just pos -> pos+1
   Nothing  -> error "positionInList: not found!"
Run Code Online (Sandbox Code Playgroud)

也许最好positionInList返回return Maybe Int,除非在没有找到文件路径时使用合理的默认值。