我有一个函数,它在计算后创建一个元组,但我想将它写入文件.
我知道如何使用文件写入文件writeFile,但不知道如何在类型签名中将计算和monad IO组合在一起.
这是我的代码.
invest :: ([Char]->Int->Int->([Char], Int) )
-> [Char]->Int->Int->([Char], Int)
invest myinvest x y = myinvest x y
myinvest :: [Char]->Int->Int->([Char], Int)
myinvest w x y
| y > 0 = (w, x + y)
| otherwise = error "Invest amount must greater than zero"
where
Run Code Online (Sandbox Code Playgroud)
我有一个函数来计算列表中的最大值,但我希望此函数从文件接收输入,然后执行最大值的计算.
maximuminvest :: (Ord a) => [a] -> a
maximuminvest [] = error "Empty Invest Amount List"
maximuminvest [x] = x
maximuminvest (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximuminvest xs
Run Code Online (Sandbox Code Playgroud)
请帮忙.谢谢.
[编辑]
第一个和第二个问题可以通过功能组合来解决,但是当我尝试它时说类型不匹配.
我检查了但是我找不到任何错误.
invest :: ( [Char]->Int->Int->([Char], Int) ) -> [Char]->Int->Int-> ([Char], Int)
invest theinvest x y = theinvest x y
theinvest :: [Char]->Int->Int-> ([Char], Int)
theinvest w x y | y > 0 = (w, x + y)
| otherwise = error "Invest amount must greater than zero"
savefile :: ([Char], Int) -> IO()
savefile (x, y) = do
let name = fst (x, y)
let temp = snd(x, y)
let amount = show temp
writeFile "C:\\Invest.txt" (name ++ " " ++ amount)
test = savefile . theinvest "asd" 1234 234
Run Code Online (Sandbox Code Playgroud)
错误消息是
ERROR - Type error in application
* Expression : savefile . invest theinvest "234" 234 234
Term : invest theinvest "234" 234 234
Type : ([Char],Int)
* Does not match : a -> b
Run Code Online (Sandbox Code Playgroud)
请帮忙.我的回报类型是([Char],Int).为什么抱怨a -> b?谢谢
我使用像savefile这样的命令来解决这个问题(投资theinvest"asd"12 12),但是为什么运营商不会这样做?
我的第四个问题是我有这样的东西["peter","1000","michell","2000","kelly","3000"],我想转换为[("peter",1000), ("michell",2000),("kelly",3000)]
文件内容的读取是好的,但我想过滤字符串并只获取数字.例如,一个文件"peter 100 \nasd 200"
我想删掉字母表并保持整数.我只想让[100,200]成为函数的参数.
请帮忙.
谢谢.
你可能想做点什么
main = do
c <- computation
writeFile "filename" (show c)
Run Code Online (Sandbox Code Playgroud)
使用Show实例写出计算结果的文件.如果您的类型足够简单,那么对于Haskell再次恢复该值,这是人类可读和可读的.
对于第二个问题,假设您的文件将值存储为
[1.5,2.3,5.1,6.3,9.8]
Run Code Online (Sandbox Code Playgroud)
然后它很容易阅读它们并执行计算:
main = do
str <- readFile "filename"
return $ computation (read str)
Run Code Online (Sandbox Code Playgroud)
应该这样做.相反,如果您的数据包含每行项目,或CSV文件或其他内容,则会涉及更多内容.对于CSV,Hackage上的Text.CSV似乎可以解决问题.
| 归档时间: |
|
| 查看次数: |
1220 次 |
| 最近记录: |