在为我的函数声明类型时,我注意到我需要从"内部"模块导入其他构造函数,仅用于此目的.这是一个(简化)示例:
import Data.Text.Encoding
import Data.Text.Internal
import Data.ByteString.Internal
foo :: Data.ByteString.Internal.ByteString -> Data.Text.Internal.Text
foo = decodeUtf8
Run Code Online (Sandbox Code Playgroud)
这些模块被命名为某种目的我相信"内部".然而,它们带有出口到公众的类型.明确依赖它们是好的做法吗?
什么情况表示[t0] -> a0 -> [a1]在此错误消息?我才意识到我必须申请(:)到foldr.为什么编译器不抱怨(*2)期望某种类型*的参数?
Prelude> foldr (:) . (* 2) [] [1..10]
<interactive>:141:19:
Couldn't match expected type `[t0] -> a0 -> [a1]'
with actual type `[a2]'
In the first argument of `* 2', namely `[]'
In the second argument of `(.)', namely `(* 2) [] [1 .. 10]'
In the expression: foldr (:) . (* 2) [] [1 .. 10]
Run Code Online (Sandbox Code Playgroud) 为什么这个定义在GHCi中失败了?
let f = (*2)+1
Run Code Online (Sandbox Code Playgroud)
同
No instance for (Num (a0 -> a0))
arising from a use of `+'
Possible fix: add an instance declaration for (Num (a0 -> a0))
In the expression: (* 2) + 1
In an equation for `f': f = (* 2) + 1
Run Code Online (Sandbox Code Playgroud)
它与以下有什么不同?
let f x = x*2+1
Run Code Online (Sandbox Code Playgroud) 如何在交互式输入的情况下更改此程序以立即处理每行文本?最好是每个换行符冲洗缓冲区.
main = do
input <- T.getContents
mapM_ T.putStrLn $ T.lines input
Run Code Online (Sandbox Code Playgroud)
更新:仍然缺少某些东西.看看(????在换行后,stdout在到达EOFstdin 后打印出来):
> cat Test.hs
import System.IO
import Data.Text as T
import Data.Text.IO as T
main = do
hSetBuffering stdout LineBuffering
input <- T.getContents
mapM_ T.putStrLn $ T.lines input
> runhaskell Test.hs
a
????
a
????
> runhaskell --version
runghc 7.6.3
>
Run Code Online (Sandbox Code Playgroud) 如何在Haskell中实现一种在命令式语言中简单易行的转换,因为它可以轻松更新地图及其内容?
while( line = next()) {
Data d = parse(line);
if( map.get(d.key) == null) map.put(d.info);
else map.get(d.key).update(d.info);
}
for(d : map.values) print d.computeResult()
Run Code Online (Sandbox Code Playgroud)
为了给出(过于简化的)具体示例,输入将包含需要通过某些规则关联的行.在这里,程序应检测到键'k'下的值被添加,更新但最终被删除,不应出现在输出中.
[time] ADD key=k, value1=V1
[time] ADD key=k, value2=V2
[time] ADD key=k, value1=ABC
[time] [...]
[time] DEL key=k
[time] ADD key=k2, value1=V1
Run Code Online (Sandbox Code Playgroud)
我应该考虑使用镜头,状态monad,按键(如果可能)或其他东西对数据进行排序?哪个是最干净的方式(至少用boilerplatte)来实现这个?我想知道这样的Haskell脚本是否比awk/sed/grep/xmlstartlet汤更容易维护.
对字符串操作库知之甚少,我想自己在Haskell中编写这些简单的转换.我很惊讶我能够生产多少样板.我该如何简化它?使用正则表达式会产生最可读的代码吗?
期望的输出:
*Main> prettyCamel "foo-bar-example" "fooBarExample" *Main> prettyCapitals "foo-bar-example" "FooBarExample"
码:
import Data.Char
prettyCapitals = foldr1 (++) . (map capitalize) . splitString
prettyCamel = foldr1 (++) . camelCase . splitString
capitalize (x:xs) = toUpper x : xs
camelCase [] = []
camelCase (x:xs) = x : (map capitalize xs)
splitString :: String -> [String]
splitString = foldr (splittingAdd (== '-')) []
splittingAdd splitPredicate char words =
if splitPredicate char
then "":words
else (char : headOrEmpty words) : tailOrEmpty words
headOrEmpty …Run Code Online (Sandbox Code Playgroud)