我想知道为什么read "1" :: Maybe Int会在运行时键入check并抛出异常.
是否有可能read返回Maybe a?那是Text.Read.readMaybe应该做的.
Prelude> read "1" :: Maybe Int
*** Exception: Prelude.read: no parse
Run Code Online (Sandbox Code Playgroud) 作为初学者,我觉得读/写/状态Monad很难理解.Monad变形金刚更加困难.我没有看到它们在其他语言中的使用,这使我有点难以将它们与我现有的Web开发体验联系起来.
是否有可能在初学者友好的Haskell中构建一个与Postgres对话的Restful API?意思是不使用像Monads/Monad变形金刚这样的高级东西.
我有一个函数readConfigFromEnv从环境变量中读取一些env var.
readConfigFromEnv :: IO (Int, String)
readConfigFromEnv = do
portStr <- getEnv "PORT"
let port = read portStr
secret <- getEnv "SECRET"
return (port, secret)
Run Code Online (Sandbox Code Playgroud)
即使Haskell有很棒的类型推理系统,我仍然想要明确指定我期望的类型,让编译器告诉我是否有任何意义:
readConfigFromEnv :: IO (Int, String)
readConfigFromEnv = do
portStr :: String <- getEnv "PORT"
let port :: Int = read portStr
secret :: String <- getEnv "SECRET"
return (port, secret)
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有编译.但是,编译器提示我应该添加语言扩展名ScopedTypeVariables.我尝试过它.
所以我的问题是:
是否添加ScopedTypeVariables了明确指定中间值类型的正确方法?
明确指定类型是一种好的做法吗?
是否有使用的副作用ScopedTypeVariables,我应该将其添加到我的默认语言扩展名列表中吗?
谢谢!
是否存在以下功能的实现?我在hoogle上找不到它
findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用以下两个函数来获取"正确"值或"正确"值.但是无法编译,为什么?
shouldBeRight :: (Show a) => Either a b -> IO b
shouldBeRight (Left a) =
throwIO $ concat ["should be Right value but wasn't, because:", show a]
shouldBeRight (Right b) = return b
shouldBeJust :: Maybe a -> IO a
shouldBeJust Nothing = throwIO "should be Just value but was Nothing"
shouldBeJust (Just a) = return a
Run Code Online (Sandbox Code Playgroud)
以下是错误:
• Ambiguous type variable ‘e0’ arising from a use of ‘throwIO’
prevents the constraint ‘(GHC.Exception.Exception
e0)’ from being solved.
Probable fix: …Run Code Online (Sandbox Code Playgroud) 我想对字符串中的字符进行排序,但没有按预期工作:
package main
import (
"fmt"
"sort"
)
func getKey(str string) string {
bs := []byte(str)
sort.Slice(bs, func(a, b int) bool {
return str[a] < str[b]
})
return string(bs)
}
func main() {
fmt.Printf("%v\n", getKey("nat"))
fmt.Printf("%v\n", getKey("tan")) // expect to get "ant", but got "atn"
fmt.Printf("%v\n", getKey("tan") == getKey("nat"))
}
Run Code Online (Sandbox Code Playgroud)
我希望它打印:
ant
ant
true
Run Code Online (Sandbox Code Playgroud)
但实际打印:
ant
atn
false
Run Code Online (Sandbox Code Playgroud)