在Haskell中,很容易编写作用于或返回元组的函数,例如prelude函数splitAt:
splitAt :: Int -> [a] -> ([a], [a])
Run Code Online (Sandbox Code Playgroud)
但有写作用于或导致功能的不容易,便捷,方式cotuples的东西呢?例如,返回Int 或 Double 的函数.举一个具体的例子,假设我想编写一个函数
MyDivision :: Int -> Int -> (Int + Double)
Run Code Online (Sandbox Code Playgroud)
其中+是我的cotupling符号,因此如果除法产生整数,MyDivision xy将x/y返回为Int,如果除法不产生整数,则返回Double.
到目前为止,似乎我有两个选择,要么声明一个新的数据类型
data IntOrDouble = AnInt Int | ADouble Double
Run Code Online (Sandbox Code Playgroud)
或使用
Either Int Double
Run Code Online (Sandbox Code Playgroud)
第一种选择需要大量输入和思考名称,第二种选择很快就会变得混乱,当你有更大的cotuples并让类型看起来像
Either (Either a (Either b c)) (Either (Either d f) g)
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一个cotuple类型,说
a + b + c + d
Run Code Online (Sandbox Code Playgroud)
我希望能够形成功能
f :: (a + b + c + d) -> e
g :: (a + b + c + d) …Run Code Online (Sandbox Code Playgroud) 在我的项目中,我有一个使用Core.Std的文件,所以我已经运行了
opam install core
Run Code Online (Sandbox Code Playgroud)
并补充说
open Core.Std
Run Code Online (Sandbox Code Playgroud)
在我的档案中.
我跑的时候
ocamlbuild myprogram.native
Run Code Online (Sandbox Code Playgroud)
它说:
Error: Unbound module Core
Run Code Online (Sandbox Code Playgroud)
指向上面的open语句.
所以,我试试这个:
ocamlbuild -use-ocamlfind -pkgs core.std myprogram.native
Run Code Online (Sandbox Code Playgroud)
并获得以下消息:
ocamlfind: Package `core.std' not found
Run Code Online (Sandbox Code Playgroud)
所以我想也许我需要运行opam install core.std,但显然根据opam没有这样的东西.我也试过"打开Core.Std ;;" 在ocaml repl中,但这也不起作用.有任何想法吗?
在Haskell中,[a]的默认排序,给定a的排序,似乎是一个词典排序(侧面问题:我在哪里可以找出是否真的如此)?我想要的是一个分级的词典排序(也称为"长度加词典"排序).
我如何指定我希望以分级的词典编纂方式进行比较?我只想要一种类型,而不是所有[a].我试过这个:
instance Ord [Int] where
compare xs ys = case compare (length xs) (length ys) of
LT -> LT
GT -> GT
EQ -> lexicographic_compare xs ys
Run Code Online (Sandbox Code Playgroud)
但收到此错误消息:
> [1 of 1] Compiling Main ( test.hs, interpreted )
test.hs:1:10:
Illegal instance declaration for `Ord [Int]'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances …Run Code Online (Sandbox Code Playgroud)