如何使用 haskell 引用不同模块中的数据声明
How to refer to data declarations in different modules with haskell
是否可以从 Main.hs 引用我的 Graph.hs -functions, edgs and vers in data Graphs a?
我想从我的 Graphs.hs 文件创建一个图形,用顶点填充它,并用边连接它们。然后我想从我的 Main.hs 文件创建一个函数 getEdges ,它可以为我列出所有边。这是可能的还是我以 OOP 方式考虑太多? :-(
下面我添加了部分代码来尝试说明我的问题。
**File Graph.hs:**
module Graph(Graph, addVertex, addEdge, connectedVertex) where
type Vertex a = a
type Edge a = (Vertex a, Vertex a)
data Graph a = Graph {
vers :: [Vertex a],
edgs :: [Edge a]
} deriving (Show, Eq, Read)
**File Main.hs:**
-- func1 to func3 is just to illustrate that there is more than one function in main.
module Main(func1, func2, getEdges, paths) where
import Graph
-- getEdges shall return a list of all edges
getEdges :: Eq a => Grap a -> [a]
getEdges g = edgs $ g
-- paths will return true if there is a connection (edges) between vertecies a to b.
paths :: Eq a => Graph a -> a -> a-> Bool
paths = undefined
如有任何帮助,我将不胜感激:-)
您在 module Graph(Graph(..), addVertex, addEdge, connectedVertex) where
中缺少一个 (..)
一个更小的同样说明性的例子:
Module.hs:
module Module(Record(..)) where
data Record a = Record {
string :: String,
int :: Int
} deriving (Show, Eq, Read)
和Main.hs:
module Main where
import Module
record = Record "Hello" 42
main =
print (string record) >>
print (int record)
Type(..)
导出类型构造函数及其关联的数据构造函数和字段访问器。您还可以在上面的示例中执行 module Module(Record(Record), int, string) where
以更精细地控制需要导出的内容。
是否可以从 Main.hs 引用我的 Graph.hs -functions, edgs and vers in data Graphs a?
我想从我的 Graphs.hs 文件创建一个图形,用顶点填充它,并用边连接它们。然后我想从我的 Main.hs 文件创建一个函数 getEdges ,它可以为我列出所有边。这是可能的还是我以 OOP 方式考虑太多? :-(
下面我添加了部分代码来尝试说明我的问题。
**File Graph.hs:**
module Graph(Graph, addVertex, addEdge, connectedVertex) where
type Vertex a = a
type Edge a = (Vertex a, Vertex a)
data Graph a = Graph {
vers :: [Vertex a],
edgs :: [Edge a]
} deriving (Show, Eq, Read)
**File Main.hs:**
-- func1 to func3 is just to illustrate that there is more than one function in main.
module Main(func1, func2, getEdges, paths) where
import Graph
-- getEdges shall return a list of all edges
getEdges :: Eq a => Grap a -> [a]
getEdges g = edgs $ g
-- paths will return true if there is a connection (edges) between vertecies a to b.
paths :: Eq a => Graph a -> a -> a-> Bool
paths = undefined
如有任何帮助,我将不胜感激:-)
您在 module Graph(Graph(..), addVertex, addEdge, connectedVertex) where
(..)
一个更小的同样说明性的例子:
Module.hs:
module Module(Record(..)) where
data Record a = Record {
string :: String,
int :: Int
} deriving (Show, Eq, Read)
和Main.hs:
module Main where
import Module
record = Record "Hello" 42
main =
print (string record) >>
print (int record)
Type(..)
导出类型构造函数及其关联的数据构造函数和字段访问器。您还可以在上面的示例中执行 module Module(Record(Record), int, string) where
以更精细地控制需要导出的内容。