如何使用大写字母在haskell中定义函数? [英] how can I define functions in haskell using uppercase letters?
问题描述
例如,如何定义使用大写字母生成斐波那契数的函数,如下所示:FIB n 我需要仅使用大写字母从终端调用该函数,如下所示:FIB 7
For example, how can I define a function to generate fibonacci numbers using uppercase letters like this: FIB n I need to call the function from the terminal using only uppercase letters like this: FIB 7
推荐答案
您不能. Haskell中的函数必须以小写unicode字符或下划线开头.以大写字母开头的符号保留用于类型和构造函数.
You can't. Functions in Haskell must start with lowercase unicode characters or an underscore. Symbols beginning with an upper case letter are reserved for types and constructors.
为什么只需要使用大写字母从终端调用函数?这似乎是一个相当武断的约束.
Why do you need to call the function from the terminal using only upper case letters? That seems like a rather arbitrary constraint.
如果您真的想阅读STDIN并进行处理,我建议写这样的内容
If you really really wanted to read STDIN and process that, I would suggest writing something like this
import System.IO
import Text.Read (readMaybe)
import Control.Monad (forever)
data Operation
= FIB Integer
| FAC Integer
| ADD Integer Integer
deriving (Read)
-- The read instance is important here
fib :: Integer -> Integer
fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
eval :: Operation -> Integer
eval (FIB n) = fib n
eval (FAC n) = product [1..n]
eval (ADD a b) = a + b
repl :: IO ()
repl = forever loop
where
parseResponse :: String -> String
parseResponse resp = case readMaybe resp of
Just op -> show $ eval op
Nothing -> "Invalid operation"
loop = do
putStr "> "
resp <- getLine
putStrLn $ parseResponse resp
main :: IO ()
main = do
hSetBuffering stdin LineBuffering
hSetBuffering stdout NoBuffering
repl
这允许用户键入数据构造函数的 exact 名称,然后您解释该数据构造函数(是的,这是一种非常简单的交互式脚本语言的全部代码,该语言只能fibs,阶乘和加法)添加到结果中.如果键入了无效的操作,它将以Invalid operation
响应.您只能使用 CTRL-C 退出解释器.
This allows the user to type in the exact name of the data constructor, then you interpret that data constructor (yes, this is the entire code for a very simple interactive scripting language that can only do fibs, factorials, and addition) into a result. If an invalid operation was typed in, it will respond with Invalid operation
. You can quit the interpreter only with CTRL-C.
这篇关于如何使用大写字母在haskell中定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!